using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyScript: MonoBehaviour
{
public bool a;
int b;
}
例如,这是我的脚本,如果a
为真,我想在检查器中显示b
,当a
为假时,在检查器中隐藏b
。
如何使我的自定义编辑器?
按如下方式添加一个新的CustomEditor脚本:
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MyScript))]
public class MyScriptEditor: Editor
{
public override void OnInspectorGUI()
{
// Call normal GUI (displaying "a" and any other variables you might have)
base.OnInspectorGUI();
// Reference the variables in the script
MyScript script = (MyScript)target;
if (script.a)
{
// Ensure the label and the value are on the same line
EditorGUILayout.BeginHorizontal();
// A label that says "b" (change b to B if you want it uppercase like default) and restricts its length.
EditorGUILayout.LabelField("b", GUILayout.MaxWidth(50));
// You can change 50 to any other value
// Show and save the value of b
script.b = EditorGUILayout.IntField(script.b);
// If you would like to restrict the length of the int field, replace the above line with this one:
// script.b = EditorGUILayout.IntField(script.b, GUILayout.MaxWidth(50)); // (or any other value other than 50)
EditorGUILayout.EndHorizontal();
}
}
}
您需要更改MyScript类中变量b的定义,如下所示:
// Hide b by default, but make it public so MyScriptEditor can access it
[HideInInspector]
public int b;
如果你愿意,你可以把所有东西压缩到MyScript类中,如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class MyScript: MonoBehaviour
{
public bool a;
//Hide b by default, but make it public so MyScriptEditor can access it
[HideInInspector]
public int b;
[CustomEditor(typeof(MyScript))]
public class MyScriptEditor: Editor
{
public override void OnInspectorGUI()
{
// Call normal GUI (displaying "a" and any other variables you might have)
base.OnInspectorGUI();
// Reference the variables in the script
MyScript script = (MyScript)target;
if (script.a)
{
// Ensure the label and the value are on the same line
EditorGUILayout.BeginHorizontal();
// A label that says "b" (change b to B if you want it uppercase like default) and restrict its length.
// You can change 50 to any other value
EditorGUILayout.LabelField("b", GUILayout.MaxWidth(50));
// Show and save the value of b
script.b = EditorGUILayout.IntField(script.b);
// If you would like to restrict the length of the int field, replace the above line with this one:
// script.b = EditorGUILayout.IntField(script.b, GUILayout.MaxWidth(50)); // (or any other value other than 50)
EditorGUILayout.EndHorizontal();
}
}
}
}
我希望这有助于您的程序的需求,并告诉我,如果你需要更多的帮助!