Dictionary usage notes in unity

Application of dictionary and serialized display on unity

public enum ColorType    //枚举类型
    {
        YELLOW,
        PURPLE,
        RED,
        BLUE,
        GREEN,
        PINK,
    }
  //定义名为colorDic的字典,<>内存放两种类型,表示两者为一一对应关系
private Dictionary<ColorType,Sprite> colorDic;

For the assignment of the dictionary, first set a structure array, manually match the sprite and color on the inspector, and finally add the contents of the structure array to the dictionary


[System.Serializable]           //在unity面板上序列化显示
    public struct colorSprite   //写成结构体的形式
    {
        public ColorType color;
        public Sprite sprite;
    }
    public colorSprite[] colorSprites;  //结构体数组

At this time, it is displayed on the unity panel, the size is set by yourself, select the color and drag the corresponding material into the Sprite (assign the structure array)
insert image description here
After setting and adding in unity successfully, push the elements in the structure array into the dictionary (note The following code should be written in the function

   //实例化字典
  colorDic = new Dictionary<ColorType, Sprite>();      
    for(int i=0;i<colorSprites.Length;i++) 
    {
       //字典中是否有了此种颜色
        if(!colorDic.ContainsKey(colorSprites[i].color))
        {
            colorDic.Add(colorSprites[i].color,colorSprites[i].sprite);
            //压入字典中
        }
    }`

Guess you like

Origin blog.csdn.net/qq_43666766/article/details/104296518