有的時候譬圣,想把某些對象如預制體瓮恭、音頻、圖片賦值到場景厘熟,不想每個資源都寫一個變量屯蹦,用list又沒法將不同的類型的對象放在一個數組里,同時想使用這些資源跟使用Resources下的資源一樣绳姨。那么接來下這個工具颇玷,就滿足了這些需求。
第一步就缆,創(chuàng)建場景資源腳本對象文件如圖
第二步帖渠,將相應資源拖到面板即可,可拖單獨文件竭宰,也可拖文件夾
到此資源就創(chuàng)建好了
第三步空郊,創(chuàng)建場景資源管理
將之前創(chuàng)建的資源腳本對象賦值到此處
第四步,獲取資源
假設想獲取的是某個音頻則代碼如下
SceneResources.Instance.Load<AudioClip>("xxxx");
這邊有個注意點切揭,就是假設狞甚,音頻文件和其他文件(如圖片)命名一樣,獲取的時候就可以加上相應的后綴,就能獲取指定對象了廓旬。
SceneResources.Instance.Load<AudioClip>("xxxx.mp3");
在如果哼审,音頻文件,有兩個同名,但是涩盾,在不同的文件夾下十气,這時候要獲取指定的,就可以通過路徑去獲取了
資源其實可以直接賦值到場景中春霍,只是這樣要修改資源的時候砸西,都要打開場景,所以這里單獨創(chuàng)建了一個資源腳本對象去管理資源址儒。這樣后續(xù)的修改就方便多了芹枷,每個場景對應一個資源腳本對象。
接下來看看代碼是如何實現的莲趣。
資源腳本對象類
using System.Collections.Generic;
using UnityEngine;
namespace WZK
{
[CreateAssetMenu(fileName = "場景資源", menuName = "創(chuàng)建場景序列化資源")]
public class ResourcesScriptableObject : ScriptableObject
{
public List<Config> _objectList = new List<Config>();
public List<string> _choseExtensionList = new List<string>();//擴展名
public int _showMin = 1;
public int _showMax = 10000;
[System.Serializable]
public class Config
{
public Object _object;//物體
public string _assetPath;//Asset下路徑
public Config(Object obj = null, string assetPath = "")
{
_object = obj;
_assetPath = assetPath;
}
}
}
}
資源腳本對象編輯類
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
namespace WZK
{
[CustomEditor(typeof(ResourcesScriptableObject))]
public class ResourcesScriptableObjectEditor : Editor
{
private ResourcesScriptableObject _resourcesScriptableObject;
private string _directionPath;//文件夾路徑
private string _fileAssetPath;//文件工程目錄
private bool _isExist;//是否已存在
private bool _isDelete;//刪除資源
public List<string> _extensionList = new List<string> { ".mp3", ".ogg", ".asset", ".txt", ".xml", ".mat", ".prefab", ".png", ".jpg" };//選擇的擴展名列表
public override void OnInspectorGUI()
{
_resourcesScriptableObject = target as ResourcesScriptableObject;
int index = -1;
for (int i = 0; i < _extensionList.Count; i++)
{
if (i % 4 == 0) EditorGUILayout.BeginHorizontal();
index = _resourcesScriptableObject._choseExtensionList.IndexOf(_extensionList[i]);
if (GUILayout.Button(_extensionList[i]))
{
if (index == -1)
{
_resourcesScriptableObject._choseExtensionList.Add(_extensionList[i]);
}
else
{
_resourcesScriptableObject._choseExtensionList.RemoveAt(index);
}
}
if((i>1&&i%4==3)||i==_extensionList.Count-1) EditorGUILayout.EndHorizontal();
}
GUILayout.Space(10);
if (_resourcesScriptableObject._choseExtensionList.Count == 0)
{
EditorGUILayout.LabelField("沒有選擇指定的后綴鸳慈,默認包含以上所有后綴!");
}
else
{
string str = "";
for (int i = 0; i < _resourcesScriptableObject._choseExtensionList.Count; i++)
{
str += _resourcesScriptableObject._choseExtensionList[i];
if (i < _resourcesScriptableObject._choseExtensionList.Count - 1)
{
str += "喧伞、";
}
}
EditorGUILayout.LabelField("選擇的后綴:"+str);
}
GUILayout.Space(10);
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("顯示區(qū)間");
_resourcesScriptableObject._showMin = EditorGUILayout.IntField(_resourcesScriptableObject._showMin);
if (_resourcesScriptableObject._showMin < 1) _resourcesScriptableObject._showMin = 1;
GUILayout.Label("~");
_resourcesScriptableObject._showMax = EditorGUILayout.IntField(_resourcesScriptableObject._showMax);
if (_resourcesScriptableObject._showMax < _resourcesScriptableObject._showMin) _resourcesScriptableObject._showMax = _resourcesScriptableObject._showMin;
GUILayout.EndHorizontal();
GUILayout.Space(10);
List<ResourcesScriptableObject.Config> objList = _resourcesScriptableObject._objectList;
for (int i = 0; i < objList.Count; i++)
{
if (i >= _resourcesScriptableObject._showMin-1&& i < _resourcesScriptableObject._showMax)
{
EditorGUILayout.BeginHorizontal();
objList[i]._object = (Object)EditorGUILayout.ObjectField("對象" + (i + 1), objList[i]._object, typeof(Object), false);
_isDelete = false;
if (GUILayout.Button("刪除" + (i + 1)))
{
_isDelete = true;
}
EditorGUILayout.EndHorizontal();
objList[i]._assetPath = EditorGUILayout.TextField("路徑" + (i + 1), objList[i]._assetPath);
GUILayout.Space(10);
if (objList[i]._assetPath == "" && objList[i]._object) objList[i]._assetPath = objList[i]._object.name;
if (_isDelete) objList.RemoveAt(i);
}
}
if (Event.current.type == EventType.DragExited)
{
System.Type type = DragAndDrop.objectReferences[0].GetType();
if (type!=typeof(DefaultAsset))
{
AddObject(objList,DragAndDrop.objectReferences[0], DragAndDrop.paths[0]);
}
else
{
_directionPath = Application.dataPath;
_directionPath = _directionPath.Substring(0, _directionPath.LastIndexOf("/") + 1) + DragAndDrop.paths[0];
if (Directory.Exists(_directionPath))
{
DirectoryInfo direction = new DirectoryInfo(_directionPath);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
for (int i = 0; i < files.Length; i++)
{
if (_resourcesScriptableObject._choseExtensionList.Count == 0 && _extensionList.Contains(Path.GetExtension(files[i].FullName)) == false)
{
continue;
}
else if (_resourcesScriptableObject._choseExtensionList.Count > 0 && _resourcesScriptableObject._choseExtensionList.Contains(Path.GetExtension(files[i].FullName)) == false)
{
continue;
}
_fileAssetPath = files[i].DirectoryName;
_fileAssetPath = _fileAssetPath.Substring(_fileAssetPath.IndexOf("Assets")) + "/" + files[i].Name;
AddObject(objList, AssetDatabase.LoadAssetAtPath<Object>(_fileAssetPath), _fileAssetPath);
}
}
}
}
GUILayout.Space(30);
if (GUILayout.Button("清空")&&EditorUtility.DisplayDialog("警告", "確定要清空所有數據嗎", "確定", "取消"))
{
_resourcesScriptableObject._objectList.Clear();
}
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(_resourcesScriptableObject);
}
/// <summary>
/// 添加音頻
/// </summary>
private void AddObject(List<ResourcesScriptableObject.Config> objList, Object obj, string assetPath)
{
//Sprite處理
if (assetPath.Contains(".png") || assetPath.Contains(".jpg"))
{
Object[] objects = AssetDatabase.LoadAllAssetsAtPath(assetPath);
if (objects.Length >= 2)
{
string tempPath = assetPath;
for (int i = 1; i < objects.Length; i++)
{
assetPath = tempPath.Substring(0, tempPath.LastIndexOf("/")+1) + objects[i].name + tempPath.Substring(tempPath.IndexOf("."));
JudgeExist(objList, objects[i], assetPath);
}
return;
}
}
JudgeExist(objList, obj, assetPath);
}
private void JudgeExist(List<ResourcesScriptableObject.Config> objList, Object obj, string assetPath)
{
_isExist = false;
assetPath = assetPath.Replace("\\", "/");
for (int i = 0; i < objList.Count; i++)
{
if (objList[i]._object == obj)
{
_isExist = true;
objList[i]._assetPath = assetPath;//如果有移動更新最新的地址
Debug.LogError("配置表里已存在該對象");
break;
}
}
if (_isExist == false) objList.Add(new ResourcesScriptableObject.Config(obj, assetPath));
}
[MenuItem("GameObject/WZK/創(chuàng)建場景資源管理對象", false,19)]
private static void CreateSoundManagerObject()
{
GameObject gameObject = new GameObject("場景資源管理");
gameObject.AddComponent<SceneResources>();
EditorUtility.FocusProjectWindow();
Selection.activeObject = gameObject;
EditorGUIUtility.PingObject(Selection.activeObject);
Undo.RegisterCreatedObjectUndo(gameObject, "Create GameObject");
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
}
}
資源獲取類
using UnityEngine;
namespace WZK
{
public class SceneResources:MonoBehaviour
{
private static SceneResources _instance;
public static SceneResources Instance
{
get { return _instance; }
}
private void Awake()
{
_instance = this;
}
private void OnDestroy()
{
_instance = null;
}
[Header("場景資源")]
public ResourcesScriptableObject _sceneResources;
/// <summary>
/// 加載資源
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name">資源名|資源路徑|資源名+后綴</param>
/// <returns></returns>
public T Load<T>(string name) where T : Object
{
return (T)_sceneResources._objectList.Find(n => n._assetPath.Contains(name))._object;
}
}
}