这里用到了一个字典替代,相当于把字典看成了struct结构,当然也可以看成一个类
代码如下
public Dictionary<FruitType, GameObject> FruitPrefabDict;
public enum FruitType
{
apple,
orange,
banana
}
[System.Serializable]
public struct FruitPrefab
{
public FruitType type;
public GameObject prefab;
}
public FruitPrefab[] FruitsPrefabs;
public void ShowDic()
{
// 字典内容
FruitPrefabDict = new Dictionary<FruitType, GameObject>();
for (int i = 0; i < FruitsPrefabs.Length; i++)
{
// FruitType t = (FruitType)Enum.Parse(typeof(FruitType), sweetPrefabs[i].type, false);
FruitType t = FruitsPrefabs[i].type;
if (!FruitPrefabDict.ContainsKey(t))
{
FruitPrefabDict.Add(t, FruitsPrefabs[i].prefab);
}
else
{
Debug.LogError("key" + "有重复");
}
}
Debug.Log(FruitPrefabDict.Count);
}
效果如下