Search Unity

  1. Unity 2020.2 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

OnValidate() called when objects are in an inconsistent state during project load.

Discussion in 'Scripting' started by tmcsweeney, Nov 21, 2014.

  1. tmcsweeney

    tmcsweeney

    Joined:
    May 24, 2011
    Posts:
    20
    When opening a project Is there a reason OnValidate() is called during deserialisation when other objects might be in an inconsistent state rather than after everything is deserialised?

    This just bit me, I have a set of SriptableObject Assets, each of which has a reference to a parent, and a list of children I use OnValidate() to keep all this in sync and ensure that each object is added to its parent's child list, and also that there aren't any children in the list that have a parent other than the current object.

    However when first loading the project OnValidate() is called as each object is deserialised, which means that since either the parent or some of the children might not have been deserialised yet, attempting to access their contents results in strange behaviour. In this case it was just causing spurious changes to the order of the child list, but it could have been much worse.

    I've worked around it for now by wrapping the entire OnValidate() logic in an if(!Application.isLoadingLevel){ } but this seems like an ugly hack, and also means that any future changes to my validation code won't actually get executed until I touch each of the objects.
     
unityunity