原文地址,多些大佬:unity切割图集并且读取图集
public class SpriteManager : MonoBehaviour
{
private static GameObject spriteManager;
private static SpriteManager instance = null;
public static SpriteManager getInstance()
{
if(instance == null)
{
instance = spriteManager.GetComponent<SpriteManager>();
}
return instance;
}
private static Dictionary<string, UnityEngine.Object[]> mAtlasDic;//图集的集合
void Awake()
{
SpriteManager.spriteManager = gameObject;
init();
}
public void init()
{
mAtlasDic = new Dictionary<string, UnityEngine.Object[]>();
}
public Sprite LoadAtlasSprite(string path, string _spriteName)
{
Sprite _sprite = FindSpriteFormBuffer(path, _spriteName);
if(_sprite == null)
{
UnityEngine.Object[] _atlas = Resources.LoadAll(path);
mAtlasDic.Add(path, _atlas);
_sprite = SpriteFormAtlas(_atlas, _spriteName);
}
return _sprite;
}
public void DeleteAtlas(string path)
{
if (mAtlasDic.ContainsKey(path))
{
mAtlasDic.Remove(path);
}
}
private Sprite FindSpriteFormBuffer(string path, string _spriteName)
{
if (mAtlasDic.ContainsKey(path))
{
UnityEngine.Object[] _atlas = mAtlasDic[path];
Sprite _sprite = SpriteFormAtlas(_atlas, _spriteName);
return _sprite;
}
return null;
}
private Sprite SpriteFormAtlas(UnityEngine.Object[] _atlas, string _spriteName)
{
for (int i = 0; i < _atlas.Length; i++)
{
if (_atlas[i].GetType() == typeof(UnityEngine.Sprite))
{
if (_atlas[i].name == _spriteName)
{
return (Sprite)_atlas[i];
}
}
}
return null;
}
}