Unity3d

来源:互联网 发布:诸暨行知小学怎么样 编辑:程序博客网 时间:2024/05/21 00:18

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,所以不要放到更新频率比较快的类下,不然性能消耗很恐怖。别问我是怎么知道的。

原创粉丝点击