Unity在编辑器模式下Load Sprite
SpriteManager
using System;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
public class SpriteManager : MonoBehavior{
[SerializeField]
public string[] filePaths ;
//private List<Sprite> spriteList;
[Serializable]
public class SpriteList {
public string name = string.Empty;
public Sprite value = null;
}
[SerializeField]
public List<SpriteList> m_SpriteList;
public Sprite GetSprite(string key) {
foreach (SpriteList sprite in m_SpriteList) {
if(sprite.name == key) {
return sprite.value;
}
}
return null;
}
}
}
SpriteEditor
using System.IO;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
[CustomEditor(typeof(SpriteManager))]
public class SpriteEditor : Editor
{
public override void OnInspectorGUI() {
base.OnInspectorGUI();
// 刷新Manager中的List
if (GUILayout.Button("Refresh SpriteList")) {
SpriteManager spriteMgr = target as SpriteManager;
for(int i = 0; i < spriteMgr.filePaths.Length; i++) {
GetFilesSprite(spriteMgr.filePaths[i], spriteMgr.m_SpriteList);
}
}
// 清空List
if (GUILayout.Button("Clear")) {
SpriteManager spriteMgr = target as SpriteManager;
spriteMgr.m_SpriteList.Clear();
}
}
// 将图片导入到Manager中
private void GetFilesSprite(string filePath, List<SpriteManager.SpriteList> spriteLists) {
string path = string.Format("{0}/{1}",Application.dataPath, filePath);
string relativePath = string.Format("{0}{1}", "Assets/", filePath);
Debug.Log(path);
Debug.Log(relativePath);
if (Directory.Exists(path)) {
DirectoryInfo direction = new DirectoryInfo(path);
FileInfo[] files = direction.GetFiles("*");
for (int i = 0; i < files.Length; i++) {
if (files[i].Name.EndsWith(".png") || files[i].Name.EndsWith(".jpg") || files[i].Name.EndsWith(".bmp")) {
SpriteManager.SpriteList item = new SpriteManager.SpriteList();
item.name = files[i].Name.Substring(0, files[i].Name.Length - 4);
string value = string.Format("{0}/{1}", relativePath, files[i].Name);
item.value = AssetDatabase.LoadAssetAtPath<Sprite>(value);
if (item.value == null)
Debug.LogError(value);
if (CheckSpriteList(item, spriteLists))
spriteLists.Add(item);
}
}
}
}
// 检查是否有重复名称
private bool CheckSpriteList(SpriteManager.SpriteList value, List<SpriteManager.SpriteList> list) {
foreach(var item in list) {
if (item.name == value.name)
return false;
}
return true;
}
}
|