Search code examples
c#unity-game-enginerace-condition

Unity 3D's component-based design model and race conditions


I'm having a bit of trouble with Unity 3D's Component-based design model.

Here's an example that demonstrates my problem:

class MyComponent : MonoBehaviour
{
    MyType entity;

    void Start() 
    {
        entity = (MyType)FindObjectsOfType(typeof(MyType)).First();
    }

    void MyMethod() 
    {
        var x = entity.SomeProperty; // <= NullReference exception
    }
}

// ....

var clone = (GameObject)Instantiate(original);
clone.GetComponent<MyComponent>().MyMethod();

Sometimes, not always though, MyMethod executes before Start so what I end up doing is move all the initializations I usually have in Start to MyMethod which is quite an ugly workaround:

    void Start() { }

    void MyMethod() 
    {
        entity = (MyType)FindObjectsOfType(typeof(MyType)).First();
        var x = entity.SomeProperty; // <= now it's fine.
    }

My question is, what is the correct way of working with this pattern (without a constructor)?


Solution

  • That probably happens when you call MyMethod from the Awake of another Component, because Awake is called before the game starts. The only solution I see is to make sure that you don't call methods on other components (in this case MyMethod) in the Awake() event, but rather in the Start() event.