2

following is my unitytest code:

        LoadScene("Scene/Level-2");
        yield return new WaitUntil(() => { return GameObject.FindObjectOfType<Arrow>(); });
        var arrow = GameObject.FindObjectOfType<Arrow>();

I load a scene and WaitUntil some object is loaded

I hope find a way to omit yield return new WaitUntil, so is there way to wait all MonoBehaviour#Start finish and then run code?

chikadance
  • 3,591
  • 4
  • 41
  • 73
  • Your current code doesn't make sense. Hard to help you without knowing what you're loading or waiting to load. What exactly are you waiting to load? Maybe show what `LoadScene` is doing? Showing what you're loading is important to get a proper answer. – Programmer Oct 09 '18 at 13:51
  • You typically want to wait until the entire scene is loaded since you don't know what additional dependencies Unity has injected. https://stackoverflow.com/questions/36272697/when-does-the-loadscene-function-in-unity-change-the-scene – jiveturkey Oct 09 '18 at 15:13

1 Answers1

8

The Awake() and Start() method is called on the first frame after an element is instantiated. So, if you load a scene and wait for the next frame, all the starts methods will be called.

This should work for you.

private IEnumerator LoadScene()
{
    // Start loading the scene
    AsyncOperation asyncLoadLevel = SceneManager.LoadSceneAsync("myLevel", LoadSceneMode.Single);
    // Wait until the level finish loading
    while (!asyncLoadLevel.isDone)
        yield return null;
    // Wait a frame so every Awake and Start method is called
    yield return new WaitForEndOfFrame();
}
Javier Bullrich
  • 389
  • 1
  • 5
  • 22
  • Awake and Start runs on first frame but it didn't mean that their execution necessarily complete before the next frame. – Muhammad Faizan Khan Oct 10 '18 at 12:14
  • Awake and Start are synchronous, that means that the frame won't continue until their execution is complete [Execution Order of Event Functions](https://docs.unity3d.com/Manual/ExecutionOrder.html). The only way that a Start method isn't "complete" is if it calls a Coroutine. – Javier Bullrich Oct 10 '18 at 18:57
  • 1
    You mean if there is no corroutine in start or Awake, then these methods will complete before the next frame at any cost. – Muhammad Faizan Khan Oct 11 '18 at 04:38