Unity3d - 动态读取Multiply的Sprites

Unity3d - 动态读取Multiply的Sprites

今日在敲代码的时候发现一个问题,就是不能用Resources.Load()读取设置了Multiply的Sprites,难道要一个一个做出来然后再一个一个读取吗?太麻烦,于是在网上搜,搜到的并不完整,自己捣鼓一番补完整。

首先开头要引用

using System.Collections.Generic

然后要定义字典

private Dictionary<string, object> spritesDictionary = new Dictionary<string, object>();

定义Sprites数组

private Sprite[] sprites;

下面是读取所有Sprites的代码。

public void LoadAllSprites()
        {
            sprites = Resources.LoadAll<Sprite>("Path");//Path是路径,Sprite是类型,改成Sprites的目录就行。当前的目录为工程目录"Assets/Resources/Path"
            for (int i = 0; i < sprites.Length; i++)
            {
                print("sprites[" + i + "]: " + sprites[i]);
                spritesDictionary.Add(sprites[i].name, sprites[i]);
            }
        }

下面是使用的代码,根据输入的string来返回Sprites

public Sprite ReadSpritesByString(string name)
        {
            Sprite a = null;
            foreach (KeyValuePair<string, object> pair in spritesDictionary)
            {
                Debug.Log(pair.Key + " " + pair.Value);
                if (pair.Key.ToString() == name)
                {
                    a = pair.Value as Sprite;
                }
            }
            return a;
        }

使用的方式就像如下这样

ABC.GetComponent<SpriteRenderer>().sprite = ReadSpritesByString("ABC");

因为里面用了foreach,所以不要写在Update或者FixedUpdate下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章