How to check if a level has loaded when using PhotonNetwork.LoadLevel()

When I use this code (the upper one) I get a message in the Log "PUN-instantiated 'Prefab' got destroyed by engine."

So, I guess I have to wait for the level to finish loading and only then I can/should instantiate.
I thought of using SceneManager.SceneLoaded but that is for LoadScene and not for the PUN's LoadLevel.
I wanna know how to wait for the level to load when using LoadLevel().

Here is the code segment:
public override void OnJoinedRoom()
{
        Debug.Log("Joined a Room.");
        
        if (PhotonNetwork.IsMasterClient)
        {
            PhotonNetwork.LoadLevel(1);
        }

        PhotonNetwork.Instantiate(Obj.name, new Vector3(0f, 5f, 0f), Quaternion.identity, 0);
}
I tried the following code but OnJoinedRoom doesn't call the LevelLoader...
public override void OnJoinedRoom()
{
        Debug.Log("Joined a Room.");
        
        if (PhotonNetwork.IsMasterClient)
        {
            LevelLoader();
        }
}

IEnumerator LevelLoader()
{
        PhotonNetwork.LoadLevel(1);

        while (PhotonNetwork.LevelLoadingProgress < 1)
        {
            yield return new WaitForEndOfFrame();
        }

        PhotonNetwork.Instantiate(Obj.name, new Vector3(0f, 5f, 0f), Quaternion.identity, 0);
}

Best Answer

  • Strike
    Strike
    Answer ✓

    Hi @swanishan,


    I guess that the Problem is solved, but I want to give an Answer for all other people, who have the same issue.

    Your code is correct BUT if you want to call a IEnumerator you have to use StartCoroutine(LevelLoader());

    Greetings,

    Strike

Answers

  • JohnTube
    JohnTube ✭✭✭✭✭
    Hi @swanishan,

    Maybe move the instantiation call (PhotonNetwork.Instantiate) to one script (e.g. inside Start()) from the new scene that is loaded.
  • Strike
    Strike
    Answer ✓

    Hi @swanishan,


    I guess that the Problem is solved, but I want to give an Answer for all other people, who have the same issue.

    Your code is correct BUT if you want to call a IEnumerator you have to use StartCoroutine(LevelLoader());

    Greetings,

    Strike