'Why can't I override "OnValidate()" in Unity3D?

So I'm implementing a curved Text class that inherits from Text. In it I have this OnValidate implementation:

protected override  void OnValidate()
{
  base.OnValidate();
  // some other code
}

Now when I try to build the project I get this error :

error CS0115: CurvedText.OnValidate() is marked as an override but no suitable method found to override

So then I was ok this is wierd even VS suggest the overriding. So what do I do next? Remove the override keyword and ignore the VS warning. So now unity throws this error :

error CS0117: UnityEngine.UI.Text does not contain a definition for OnValidate 

So what do I do now ? I should also mention that when the script is added to a object in the scene it works just as expected and no errors are being thrown.



Solution 1:[1]

Because OnValidate is part of the Unity3D Messaging System.

And as this blog mentions this messaging function will only resolved when a MonoBehaviour Object first time is accessed and the underlying script is inspected through scripting runtime (either Mono or IL2CPP).

So right now, for the compilier, ther is no OnValidate to override.

Simply call the method like this:

void OnValidate()
{
   // some other code
}

My 2 Cents to the comments

  • The protected Keyword doesn't prevent things from being overwritten.

  • The virtual Keyword is used to modify things and allowing them to be overridden in a derived class. This means you cannot override a non-virtual method.

Solution 2:[2]

It is possible to override OnValidate() if you explicitly make it editor only by using a preprocessor directive.

Unity documentation for OnValidate() states "Called in the editor only": https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnValidate.html

So, you can prevent both the VS complaint and the compiler error by using a preprocessor directive #if UNITY_EDITOR when overriding OnValidate(). This is also more explicit about what the code does instead of relying on insight on Unity internals, hence more readable.

It is probably hidden from builds behind the scenes as an editor-only code, but that hack is broken somehow when it is overridden.

#if UNITY_EDITOR
    protected override void OnValidate()
    {
        // Do something.
    }
#endif // UNITY_EDITOR

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2