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下

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