How to wait that a GameObject instance has completed own Start from another GameObject instance's Start with Unity?

Viewed 2093

I have two GameObjects like this:

public class GOA : MonoBehaviour
{
    void Start()
    {
     ... do something ...
    }
}

and another object that depends from the first in this way:

public class GOB : MonoBehaviour
{
    void Start()
    { 
     // wait GOA has terminated own "Start" life cycle
     ... then do something ... 
    }
}

How can I make GOB:Start() to wait until GOA:Start() has terminated?

3 Answers

Start method can be a coroutine.
You can write something like this:

public class GOA : MonoBehaviour
{
    public bool IsInitialized { get; private set;}

    void Start()
    {
        ... do something ...
        IsInitialized = true;
    }
}

And Here's your GOB script:

public class GOB : MonoBehaviour
{
    public GOA aInstance;
    IEnumerator Start()
    { 
     // wait GOA has terminated own "Start" life cycle
     yield return new WaitUntil(() => aInstance.IsInitialized);
     ... then do something ... 
    }
}

Also don't forget to include using System.Collections.Generic; in GOB script.

It seeems to me that you are looking for Script Execution Order (https://docs.unity3d.com/Manual/class-MonoManager.html). Edit-> project setting -> script Execution Order. Use the '+' to add scripts.

Set GOA to -100 and GOB to +100. That wat GOA Will have its start method called before GOB's start method.

I already had to do that thing, cascade initialisation. The trick I found was this one :

public class GOA : MonoBehaviour
{
    public bool isInitialized = false;

    void Start()
    {
        // ... do something ...
        isInitialized = true;
    }
}

And then, in class B, I initialize in Update() method. I'm using a boolean to make sure the initialisation will occur only once

public class GOB : MonoBehaviour
{
    public bool isInitialized = false;
    var a = GameObject.Find("A");

    void Update() //Update ! Not Start()
    {
        if (!isInitialized  && a.GetComponent<GOA>().isInitialized)
        {
            // initialize B...
            isInitialized = true;
        }
    }
}
Related