nity编辑器据说可以写很多的插件,了解过还没有怎么写过,这次试了试,搞了一会,终于搞出来了。
1.新建两个C#代码脚本,一个命名为NPC,另一个为NPCEditor。并且新建一个文件夹命名为Editor,将NPCEditor脚本放入其中。如图1-1
2.NPC脚本的代码如图2-1
3.NPCEditor的脚本如下:
[csharp]view plaincopy
print?
usingUnityEngine;
usingUnityEditor;
usingSystem.Collections;
[CustomEditor(typeof(NPC))]
publicclassNPCEditor : Editor {
//声明脚本对象
privateSerializedObject npc;
//声明属性值
privateSerializedProperty mynpc;
privatestaticboolfolds =false;
privateNPC Target
{get{return(NPC)target;}}
//ui显示处理,加减数组随想数量的处理
privatestaticGUIContent
insertContent =newGUIContent("+","duplicate this npc"),
deleteContent =newGUIContent("-","delete this npc");
//限定按钮的宽度
privatestaticGUILayoutOption
buttonWidth = GUILayout.MaxWidth(20f);
voidOnEnable()
{
//给脚本对像和属性赋值
npc=newSerializedObject(target);
mynpc=npc.FindProperty("mynpc");
}
publicoverridevoidOnInspectorGUI()
{
npc.Update();
EditorGUILayout.Space();
GUI.changed =false;
// 创建NPC
folds = EditorGUILayout.BeginToggleGroup("创建NPC", folds);
if(folds)
{
EditorGUILayout.Space();
//确保对象数量为0时可以添加。
if(GUILayout.Button(insertContent, EditorStyles.miniButtonLeft, buttonWidth))
{
mynpc.arraySize=1;
}
//根据对象数组的长度,循环新建npc
for(inti=0;i
{
SerializedProperty npc_s=mynpc.GetArrayElementAtIndex(i);
EditorGUILayout.BeginVertical();
EditorGUILayout.PropertyField(npc_s.FindPropertyRelative("id"));
EditorGUILayout.PropertyField(npc_s.FindPropertyRelative("name"));
EditorGUILayout.PropertyField(npc_s.FindPropertyRelative("pos_x"));
EditorGUILayout.PropertyField(npc_s.FindPropertyRelative("pos_y"));
EditorGUILayout.BeginHorizontal();
//增加
if(GUILayout.Button(insertContent, EditorStyles.miniButtonLeft, buttonWidth)){
mynpc.InsertArrayElementAtIndex(i);
}
//减少
if(GUILayout.Button(deleteContent, EditorStyles.miniButtonRight, buttonWidth)){
mynpc.DeleteArrayElementAtIndex(i);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
if(GUILayout.Button("Update"))
{
//这里可以写处理数据的脚本
}
npc.ApplyModifiedProperties();
}
EditorGUILayout.EndToggleGroup();
}
}
4.在场景中新建一个空对象,并挂上NPC脚本,如图4-1: