Search Unity

OnValidate gets called at startup before properties in other components have deserialized

Discussion in 'Scripting' started by MattRix, Jan 23, 2017.

  1. MattRix

    MattRix

    Joined:
    Aug 23, 2011
    Posts:
    121
    I have some code in OnValidate() that is accessing a property in another component. I'm pretty sure this used to work fine when I was using Unity 5.0, but now that I'm in 5.5, the property in the other component has not yet been deserialized. This seems pretty strange, am I missing something?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    OnValidate is, I think, not intended to access data in other components, and as such its execution order should not be relied on.

    You may be able to work around this by validating on both sides, e.g.:
    Code (csharp):
    1.  
    2.  
    3. // ComponentA.cs
    4.  
    5. [System.NonSerialized]
    6. public bool isDeserialized = false;
    7. public ComponentB b;
    8. void OnValidate() {
    9. if (b != null && b.isDeserialized) {
    10. b.SomeFunction();
    11. }
    12. isDeserialized = true;
    13. }
    14.  
    15. // ComponentB.cs
    16. [System.NonSerialized]
    17. public bool isDeserialized = false;
    18. public ComponentA a;
    19. void OnValidate() {
    20. if (a != null && a.isDeserialized) {
    21. SomeFunction();
    22. }
    23. isDeserialized = true;
    24. }
    25.  
    26. public void SomeFunction() {
    27. // validation code for two classes here
    28. //will be called every OnValidate for either script, but only if both are deserialized
    29. }