Race conditions using Instantiate

Hey!

I have a question because I can’t understand how does it work actually.

Let’s say I’ve got this code:

PlayerFactory:

public class PlayerFactory : MonoBehaviour
{
    [SerializeField]
    private GameObject _playerPrefab;

    public Player Create()
    {
        GameObject gameObject = Instantiate(_playerPrefab);
        Player player = gameObject.GetComponent<Player>();

        var someInitVariable = 5;
        player.Initialize(someInitVariable);

        return player;
    }
}

Player:

public class Player : MonoBehaviour
{
    private int _initVariable;

    public void Initialize(int someInitVariable) 
    {
        _initVariable = someInitVariable;
    }

    private void Start() 
    {
        SomeStaticManager.DoSomething(_initVariable);
    }
}

Please explain me, having this example - why the Start method is not called before the Initialize method? I thought, that after using Instantiate, the GameObject will be instantiated on the scene and immediately started - so I’ve expected a race condition here, but there’s none. Why? I’d really appreciate any insight into this because I’d like to understand how it really works.

Thanks in advance!

If you read the documentation of the Start method the first sentence reads:

Start is called on the frame when a
script is enabled just before any of
the Update methods is called the first time.

So Start will be called right before the next Update should be called. If your object is instantiated during Update, Start of the newly created object will be called the next frame. If your object is instantiated inside another classes Start method, the Start method of the new object may be executed this or next frame. However Start is never called from inside Instantiate unlike Awake. OnEnabled and Awake is called before Instantiate returns (at least when the gameobject is instantiated active and enabled).

Unity’s scripting environment is single threaded. Since Start isn’t called inside any of the methods you use in your Create method Start can only be invoked by the engine once your Create method (and the caller method is finished).

It’s actually quite difficult to actually get a race condition in Unity. There may be ordering problems but never real race conditions as they require at least two threads.