
在本教程中,将了解如何在unity3D中创建自定义检查器,自定义检查器允许在Unity软件中为组件创建或扩展检查器功能。
要在unity中创建自定义检查器,需要下面俩点:
- 从编辑器类继承脚本。
- 覆盖OnInspectorGUI方法。
unity中的自定义检查器
下面提到的脚本是unity中的示例自定义检查器脚本。
using UnityEditor;
using UnityEngine;
// provide the component type for which this inspector UI is required
[CustomEditor(typeof(SampleScript))]
public class CustomInspector : Editor
{
public override void OnInspectorGUI()
{
// will enable the default inpector UI
base.OnInspectorGUI();
// implement your UI code here
}
}
将在这里看到一些示例来扩展自定义编辑器。
按钮:
//Button
if (GUILayout.Button("Test Button"))
{
Debug.Log("Test Button Clicked");
}

将输入值应用于游戏对象。
示例脚本:将显示自定义检查器的Monobehaviour脚本。
using UnityEngine;
public class SampleScript : MonoBehaviour
{
public float scale { get; set; }
}
自定义检查器
using UnityEditor;
using UnityEngine;
// provide the component type for which this inspector UI is required
[CustomEditor(typeof(SampleScript))]
public class CustomInspector : Editor
{
public override void OnInspectorGUI()
{
// will enable the default inpector UI
base.OnInspectorGUI();
// implement your UI code here
var style = new GUIStyle(GUI.skin.label);
style.alignment = TextAnchor.MiddleCenter;
style.fontStyle = FontStyle.Bold;
EditorGUILayout.LabelField("Settings", style, GUILayout.ExpandWidth(true));
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Scale: ");
SampleScript sampleScript = (SampleScript)target;
sampleScript.scale = EditorGUILayout.FloatField(sampleScript.scale);
GUILayout.EndHorizontal();
//Button
if (GUILayout.Button("Test Button"))
{
sampleScript.gameObject.transform.localScale = new Vector3(sampleScript.scale, sampleScript.scale, sampleScript.scale);
}
}
}
如图:

还可以修改Monobehaviour脚本以进行检查器自定义。
[Header("Transform Inputs")]
[Tooltip("Sample tooltip")]
public int TestValue;
标题和工具提示
- 标头有助于对检查器字段进行分组。
- 工具提示将显示在该字段的鼠标悬停上。

上下文菜单
使用上下文菜单属性,可以在组件设置中添加选项和相应的功能。
[ContextMenu("SampleContext")]
public void MyMethod()
{
Debug.Log("Clicked from context menu");
}

…
以上是3D天堂关于在Unity中创建自定义检查器的全部内容,如果你有任何反馈,请随时在本页面下方留言。