Created
December 14, 2015 06:57
-
-
Save anonymous/d3387c93983b12628264 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
using System.Collections.Generic; | |
using NUnit.Framework; | |
// LINK: http://answers.unity3d.com/questions/736237/how-to-load-sprite-at-runtime-from-atlas.html | |
public class SpriteManager : SingletonBehaviour<SpriteManager> | |
{ | |
[SerializeField] List<Sprite> ReticleSprites = new List<Sprite>(); | |
[SerializeField] List<Sprite> ItemSprites = new List<Sprite>(); | |
[SerializeField] List<Sprite> HelpUISprites = new List<Sprite>(); | |
Dictionary<string, Sprite> spriteDict; | |
// copy list into dict for faster lookup | |
void Awake() | |
{ | |
Assert.Greater(ReticleSprites.Count, 0); | |
Assert.Greater(ItemSprites.Count, 0); | |
Assert.Greater(HelpUISprites.Count, 0); | |
var spriteCount = ReticleSprites.Count + ItemSprites.Count + HelpUISprites.Count; | |
spriteDict = new Dictionary<string, Sprite>(spriteCount); | |
addSpriteListToDict(ReticleSprites, "ReticleSprites"); | |
addSpriteListToDict(ItemSprites, "ItemSprites"); | |
addSpriteListToDict(HelpUISprites, "HelpUISprites"); | |
} | |
public Sprite GetSprite(string spriteName) | |
{ | |
Sprite sprite; | |
if(!spriteDict.TryGetValue(spriteName, out sprite)) | |
{ | |
Debug.LogWarning(string.Format("SpriteCollection.GetSprite: no sprite found for key {0}, returning null", spriteName)); | |
return null; | |
} | |
return sprite; | |
} | |
void addSpriteListToDict(IList<Sprite> spriteList, string listName) | |
{ | |
for (int i = 0; i < spriteList.Count; i++) | |
{ | |
Sprite sprite = spriteList[i]; | |
if(sprite == null) | |
{ | |
Debug.Log(string.Format("SpriteCollection.addSpriteListToDict: slot {0} empty in sprite list {1}, continuing", i, listName)); | |
continue; | |
} | |
Assert.False(spriteDict.ContainsKey(sprite.name), "duplicate sprite name (" + sprite.name + ")"); | |
spriteDict.Add(sprite.name, sprite); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment