Unity Editor OnInspectorGUI的重写与面板的创建
对编辑器类的相关操作我们都是放在Unity文件夹下的Editor目录下的。
OnInspectorGUI()是Unity的Editor类里的相关函数,通过对该方法的重写,可以自定义对Inspector面板的绘制。
using UnityEngine;
using System.Collections;
public class Test1 : MonoBehaviour
{
public bool myBool;
public string myString;
}
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Test1))]
public class Test1Editor : Editor
{
public override void OnInspectorGUI()
{
Test1 test = (Test1) target;
test.myBool = EditorGUILayout.Toggle("是否选中", test.myBool);
test.myString = EditorGUILayout.TextField("输入文本",test.myString);
}
}
达到了重新自定义绘制这一面板的功能。
EditorWindow可以用来创建面板,如下代码所示:
using UnityEngine;
using UnityEditor;
public class Test2Editor : EditorWindow
{
[MenuItem("MyEditor/CreatWindow")]
static void AddWindow()
{
Rect wr = new Rect(0, 0, 500, 500);
Test2Editor window = (Test2Editor)EditorWindow.GetWindowWithRect(typeof(Test2Editor), wr, true, "CreatWindow");
window.Show();
}
private string text;
//绘制窗口时调用
void OnGUI()
{
text = EditorGUILayout.TextField("输入文字:", text);
if (GUILayout.Button("打开通知", GUILayout.Width(200)))
{
this.ShowNotification(new GUIContent("This is a Notification"));
}
if (GUILayout.Button("关闭通知", GUILayout.Width(200)))
{
this.RemoveNotification();
}
if (GUILayout.Button("关闭窗口", GUILayout.Width(200)))
{
this.Close();
}
}
void OnFocus()
{
Debug.Log("获得焦点时调用一次");
}
void OnLostFocus()
{
Debug.Log("丢失焦点时调用一次");
}
void OnHierarchyChange()
{
Debug.Log("Hierarchy视图中的任何对象发生改变时调用一次");
}
void OnProjectChange()
{
Debug.Log("Project视图中的资源发生改变时调用一次");
}
void OnInspectorUpdate()
{
Debug.Log("面板的更新");
this.Repaint();
}
void OnSelectionChange()
{
//处于开启状态,并且在Hierarchy视图中选择某游戏对象时调用
foreach (Transform t in Selection.transforms)
{
Debug.Log("OnSelectionChange" + t.name);
}
}
void OnDestroy()
{
Debug.Log("关闭时调用");
}
}
通过以上代码,会在Unity的菜单栏增加一项,点击时就会弹出面板。
结束。