Search Unity

Question Player prefab destroyed when loading into another scene

Discussion in 'Lobby' started by elzbeb, Jan 18, 2023.

  1. elzbeb

    elzbeb

    Joined:
    Jul 30, 2020
    Posts:
    54
    Hey so I have 2 scenes, one that has the UI and the other which is the real map where you spawn, when you click a button on the first scene it loads just fine, but when I try to move it logs this error

    MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
    Your script should either check if it is null or you should not destroy the object.


    I tried using the dontdestroyonload but it doesn't seem to be working. Here is a video and the code

    This is called in the NetworkManagerUI which is a child of the canvas


    Code (CSharp):
    1. startHostButton?.onClick.AddListener(async () =>
    2.         {
    3.             await Authenticate();
    4.             _connectedLobby = await CreateLobby();
    5.             NetworkManager.SceneManager.LoadScene("GameScene", LoadSceneMode.Single);
    6.             // Test();
    7.         });

    Here is a script attached to the player prefab that executes on spawn

    Code (CSharp):
    1.     public override void OnNetworkSpawn()
    2.     {
    3.         base.OnNetworkSpawn();
    4.         DontDestroyOnLoad(gameObject);
    5.         if (IsLocalPlayer)
    6.         {
    7.             Debug.Log("CREATED 1");
    8.             Starter.instance._cinemachineVirtualCamera.Follow = camTarget;
    9.             // Starter.instance._cinemachineVirtualCamera.LookAt = transform;
    10.             Starter.instance._cinemachineVirtualCamera.enabled = true;
    11.         }
    12.         Debug.Log("CREATED 2");
    13.         var cc = GetComponent<CharacterController>().enabled = IsClient;
    14.         var tp = GetComponent<ThirdPersonController>().enabled = IsClient;
    15.         var rp = GetComponent<BasicRigidBodyPush>().enabled = IsOwner;
    16.         var sa = GetComponent<StarterAssetsInputs>().enabled = IsOwner;
    17.         var pi = GetComponent<PlayerInput>().enabled = IsOwner;
    18.      
    19.         transform.position = spawnPoint.position;
    20.         transform.rotation = spawnPoint.rotation;
    21.     }