Improbable Icon

Unity lifecycle && SpatialOS

bestpractice
v9-0-0

#1

From the man, the legend: @andrew
The rule of thumb should be:

  • Call static initialization on Awake – eg. GetComponent<>; Setting variables etc.
  • Call SpatialOs initialization onEnable – eg. OnComponentUpdated callbacks etc.

Another thing that catches people off guard a lot of the time, is that when you use pooling. Awake will not get called between the object being used for different Entities.

What I mean is that your object may get reused:

  • Awake is called for ObjectA
  • ObjectA is now Entity 4
  • OnEnable is called
  • OnDisabled is called
  • Object A is now nothing – returned to the pool
  • Object A is now Entity 5
  • OnEnable is called
  • OnDisabled is called

Note that Awake is only called once per object (and not once for each entity) (edited)

(One more tip: Start is called after OnEnable and your readers and writers will be available. But due to the pooling thing above it will only ever get called on the first time it is enabled. Therefore there are very few valid use cases for using it)


#2

For more info on this (unity side) Execution Order of Event Functions