整理了一下ScriptableObject的用法,避免在创建ScriptableObject的时候重复修改代码,特地做了一个编辑器。主要是通过反射找出所有的ScriptableObject类型的.CS文件,然后生成对应名字的asset文件。
- 找出所有的ScriptableObject类型,传给自定义的窗口
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
public class ScriptableObjectFactory {
[MenuItem("Assets/Create/ScriptableObject")]
public static void CreateScritableObject()
{
var assembly = GetAssembly();
// 获取此程序集中定义的类型。
var types = assembly.GetTypes();
List<Type> list = new List<Type>();
for (int i = 0; i < types.Length; i++)
{
//确定当前Type是否派生自指定的Type
if (types[i].IsSubclassOf(typeof(ScriptableObject)))
{
list.Add(types[i]);
}
}
ScriptableObjectWindow.Init(list.ToArray());
}
//加载程序集。Unity3D 是基于 Mono的,我们平时写的 C# 脚本都被编译到了 Assembly-CSharp.dll
private static Assembly GetAssembly()
{
return Assembly.Load(new AssemblyName("Assembly-CSharp"));
}
}
- 通过自定义的窗口来创建选中的ScriptableObject类型.默认放到Asset路径下。如果存在会弹出窗口提示提示是否继续创建。
using UnityEngine;
using System.Collections;
using UnityEditor;
using System;
using System.Linq;
using UnityEditor.ProjectWindowCallback;
using System.IO;
public class ScriptableObjectWindow : EditorWindow {
private int selectIndex;
private static Type[] types;
private static string[] names;
private static Type[] Types
{
get{return types;}
set
{
types = value;
names = types.Select(t => t.FullName).ToArray();
}
}
public static void Init(Type[] scriptableObjects)
{
Types = scriptableObjects;
var window = EditorWindow.GetWindow<ScriptableObjectWindow> (true, "Create a new ScriptableObject", true);
window.ShowPopup();
}
public void OnGUI()
{
var tipLabel = new GUIStyle(GUI.skin.label);
tipLabel.normal.textColor = Color.green;
tipLabel.fontSize = 15;
EditorGUILayout.BeginHorizontal();
GUILayout.Label("All ScriptableObject",tipLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
selectIndex = EditorGUILayout.Popup(selectIndex, names);
if (GUILayout.Button("Create"))
{
string path = "Assets";
var asset = ScriptableObject.CreateInstance (types [selectIndex]);
string assetPath = string.Format("{0}/{1}.asset", path, names[selectIndex]);
if (File.Exists(assetPath))
{
bool isCreate = ShowConfirm("提示", "文件已存在是否从新创建?");
if (!isCreate)
{
return;
}
}
AssetDatabase.CreateAsset(asset, assetPath);
ShowAlert ("提示", "创建成功" , "确定");
}
}
public void ShowAlert(string title, string msg, string okText)
{
if(EditorUtility.DisplayDialog (title, msg , okText))
{
}
}
public bool ShowConfirm(string title, string msg, string cancelButtonText = "取消", string okButtonText = "确定")
{
if (EditorUtility.DisplayDialog(title, msg, okButtonText, cancelButtonText))
{
return true;
}
else
{
return false;
}
}
}