JoeyL
JoeyL

Reputation: 1305

Unity - Is it possible to access OnValidate() when using a custom inspector?

I recently made a custom inspector and I just realized that my OnValidate() is not being called when I edit a variable in the Inspector. Any ideas on how to get my calls back to OnValidate() again while keeping the custom inspector I used?

Upvotes: 9

Views: 8253

Answers (2)

Vincent Gilabert
Vincent Gilabert

Reputation: 53

For those who just need to check for a change in their custom overriden editor and realized that the OnValidate() action is not triggered on change by default, like in default inspector, alternatively you can use this line EditorGUI.BeginChangeCheck() For exemple you can use it this way :

[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);
        // Declare all other properties you want to check for changes here
        
        // This will be called every time one of the above properties is modified in your custom editor
        if (EditorGUI.EndChangeCheck())
        {
            if (class.autoUpdate)
            {
                class.DoSomething();
            }
        }
    }
}

Upvotes: 0

JoeyL
JoeyL

Reputation: 1305

The answer was in serializing and propertyfield.

Example with my code, the first part here is just showing that in my main script I have this declared. Remember now, public variables are already serialized so no need to put that.

public class Original : MonoBehaviour {

// Used for the user to input their board section width and height.
[Tooltip("The desired Camera Width.")]
public float cameraWidth;
}

Now in my Custom inspector I have this:

    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();
         }
    }

Upvotes: 2

Related Questions