Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Third Party ReplacePlayerForConnection Mirror

Discussion in 'Multiplayer' started by carlosmotaa, Dec 8, 2022.

  1. carlosmotaa

    carlosmotaa

    Joined:
    Jan 1, 2018
    Posts:
    8
    Hi all,
    I have problems executing the ReplacePlayerForConnection function, I get the error: NullReferenceException: Object reference not set to an instance of an object on the line: GameObject oldPlayer = conn.identity.gameObject;

    I'm trying to replace the player's gameobject based on the gamemode: the entire code is:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Mirror;
    5. using UnityEngine.SceneManagement;
    6.  
    7. public class ClassController : NetworkManager
    8. {
    9.     public NetworkConnectionToClient connectionToClient;
    10.     public GameObject playerRun;
    11.     //
    12.  
    13.     private void Start()
    14.     {
    15.  
    16.     }
    17.     private void Update()
    18.     {
    19.         SceneManager.sceneLoaded += OnSceneLoaded;
    20.     }
    21.     public void OnSceneLoaded(Scene Run, LoadSceneMode Single)
    22.     {
    23.  
    24.         ReplacePlayer(connectionToClient, playerRun);
    25.  
    26.     }
    27.     public void ReplacePlayer(NetworkConnectionToClient conn, GameObject newPrefab)
    28.     {
    29.         // Cache a reference to the current player object
    30.         GameObject oldPlayer = conn.identity.gameObject;
    31.  
    32.         // Instantiate the new player object and broadcast to clients
    33.         // Include true for keepAuthority paramater to prevent ownership change
    34.         NetworkServer.ReplacePlayerForConnection(conn, Instantiate(newPrefab), true);
    35.  
    36.         // Remove the previous player object that's now been replaced
    37.         // Delay is required to allow replacement to complete.
    38.         Destroy(oldPlayer, 0.1f);
    39.     }
    40.  
    41.  
    42. }
    What I can be doing wrong?