unity加载图片并放进内存

public const string TaskHead = "ResImages/task";
public const string WiseManHead = "ResImages/wiseman";
public const string GeneralHead = "ResImages/general";
public const string ArtisanHead = "ResImages/artisan";
public const string TraderHead = "ResImages/trader";

//AutoGudeNPC
public const int NPCWiseMan = 0;
public const int NPCGeneral = 1;
public const int NPCArtisan = 2;
public const int NPCTrader = 3;

通过路径加载图片

private Dictionary<string, Sprite> spDic = new Dictionary<string, Sprite>();
public Sprite LoadSprite(string path, bool cache = false) {
Sprite sp = null;
if (!spDic.TryGetValue(path, out sp)) {

sp = Resources.Load<Sprite>(path);
if (cache) {
spDic.Add(path, sp);
}
}
return sp;

}

 

private void SetSprite(Image img,string path) {

Sprite sp = LoadSprite(path, true);
img.sprite = sp;

}

最后通过id使用

private void SetGudieBtnIcon(int npcID) {

string spPath = "";
Image img = btnGuide.GetComponent<Image>();
switch (npcID) {
case Constans.NPCWiseMan:
spPath = PathDefine.WiseManHead;
break;
case Constans.NPCGeneral:
spPath = PathDefine.GeneralHead;
break;
case Constans.NPCArtisan:
spPath = PathDefine.ArtisanHead;
break;
case Constans.NPCTrader:
spPath = PathDefine.TraderHead;
break;

}
SetSprite(img, spPath);
}

posted @ 2021-06-05 11:34  T驱动  阅读(188)  评论(0编辑  收藏  举报