我最近制作了一个自定义检查器,我刚刚意识到当我在检查器中编辑变量时,我的 OnValidate() 没有被调用。 关于如何在保留我使用的自定义检查器的同时再次调用 OnValidate() 有什么想法吗?
答案在于序列化和属性字段。
以我的代码为例,这里的第一部分只是显示在我的主脚本中我已经声明了这个。现在请记住,公共变量已经序列化,因此无需放置它。
public class Original : MonoBehaviour {
// Used for the user to input their board section width and height.
[Tooltip("The desired Camera Width.")]
public float cameraWidth;
}
现在在我的海关检查员中我有这个:
pubilc class Original_Editor : Editor{
public override void OnInspectorGUI(){
serializedObject.Update();
// Get the camera width.
SerializedProperty width = serializedObject.FindProperty("cameraWidth");
// Set the layout.
EditorGUILayout.PropertyField(width);
// Clamp the desired values
width.floatValue = Mathf.Clamp((int)width.floatValue, 0, 9999);
// apply
serializedObject.ApplyModifiedProperties();
}
}
对于那些只需要在自定义重写编辑器中检查更改并意识到默认情况下不会在更改时触发 OnValidate() 操作的人,就像在默认检查器中一样,或者您可以使用此行
EditorGUI.BeginChangeCheck()
例如,您可以这样使用它:
[CustomEditor(typeof(AnyClass))]
public class AnyClassEditor : Editor
{
public override void OnInspectorGUI()
{
AnyClass class = (AnyClass) target;
EditorGUI.BeginChangeCheck();
class.autoUpdate = EditorGUILayout.Toggle("Auto Update", class.autoUpdate);
if (EditorGUI.EndChangeCheck())
{
if (class.autoUpdate)
{
class.DoSomething();
}
}
}
}