//Switch分支语句用法
private int number;
public void Test()
{
number = Random.Range(1, 7);
Switch();
}
void Switch()
{
switch (number)
{
case 1: case 2: Debug.Log("矿泉水");break;
case 3:Debug.Log("红茶");break;
case 4:Debug.Log("绿茶");break;
case 5:Debug.Log("雪碧");break;
case 6:Debug.Log("可口可乐");break;
default:Debug.Log("脉动");break;//default可以没有
}
}
//数组声明和赋值
private int[] age={1,1,1,1,1,1,1};//声明数组并赋值 数组的数据有下标(索引)
private int[] ages = new []{10};//默认值为0
private int[] ages = new int[]{10,1,11,1};//默认值为0
//单例模式的初始化
#region 单例模式
private static Knapsack _instance;
public static Knapsack Instance
{
get
{
if (_instance == null)
{
_instance = GameObject.Find("Knapsack").GetComponent<Knapsack>();
}
return _instance;
}
}
#endregion
//单例模式的调用
Knapsack tempKnapsack = Knapsack.Instance;//初始化
tempKnapsack.DisplaySwitch();调用方法
-
什么时候使用字典
-
当我们在操作大型的列表时候,该用字典会更为便利 比如我们的道具系统,玩家购买道具的时候,发出指令(输入对应的物品 id) 如果使用列表,我们需要遍历整个列表来查找该物品,而使用字典的话可以直接通过 key 和 value 配对找到 另外比如我们的物品栏,每个空格对应一个 key,然后可以链接不同的物品(即 value)
-
实例化:Dictionary<键key, 值value> 名字dic = new Dictionary<键key, 值value>();
Dictionary<Tkey, Tvalue> Dic = new Dictionary<Tkey, Tvalue>();
常见方法:
添加:Dic.Add(key,value)给字典添加值
删除:Dic.Remove(key) 删除指定值
访问:Dictionary[key] 表示key所对应的值
判断空:ContainsKey(key)判断key是否存在
嵌套字典
嵌套实例化:Dictionary<key, Dictionary<key, value>> dic = new Dictionary<key, Dictionary<key, value>>();
/**************************************************** * 功能:解析txt文本功能并存储于字典中 *****************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; public class LoadText : MonoBehaviour { public Dictionary<int, string> book = new Dictionary<int, string>(); void Start() { // 将test中的内容加载进txt文本中 string txt = File.ReadAllText(Application.streamingAssetsPath + "/1.txt"); // 以换行符作为分割点,将该文本分割成若干行字符串,并以数组的形式来保存每行字符串的内容 string[] strs = txt.Split('\n');//回车 // 将每行字符串的内容以逗号作为分割点,并将每个逗号分隔的字符串内容遍历输出 遍历输出全部字符串 for (int i = 1; i < strs.Length; i++) { string[] ss = strs[i].Split('\t'); //tab book.Add(Convert.ToInt32(ss[0]),ss[1]); } Debug.Log(book[5]); } }