Skip to content

Instantly share code, notes, and snippets.

/SpriteManager.cs
Created Dec 14, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.