Search Unity

NullReferenceException when trying to use NetworkManager.SpawnWithClientAuthority

Discussion in 'Scripting' started by VDavid003, Jul 28, 2018.

  1. VDavid003

    VDavid003

    Joined:
    Dec 3, 2016
    Posts:
    3
    So I want to create a 2d multiplayer game, and I have a gameobject as a player prefab that spawns the actual player when it spawns, and when I try it out with 2 players (1 build and 1 editor), the second player doesn't spawn on the server, and the client (editor) shows this error:

    NullReferenceException: Object reference not set to an instance of an object
    UnityEngine.Networking.NetworkServer.SpawnWithClientAuthority (UnityEngine.GameObject obj, UnityEngine.Networking.NetworkConnection conn) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkServer.cs:1565)
    Connection.CmdSpawn () (at Assets/Scripts/Connection.cs:20)
    Connection.Start () (at Assets/Scripts/Connection.cs:10)

    The code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5. public class Connection : NetworkBehaviour {
    6.     public GameObject pobjPrefab;
    7.     // Use this for initialization
    8.     void Start () {
    9.         if (!isLocalPlayer) { return; }
    10.         CmdSpawn();
    11.     }
    12.  
    13.     // Update is called once per frame
    14.     void Update () {
    15.      
    16.     }
    17.     void CmdSpawn()
    18.     {
    19.         GameObject pobj = (GameObject)Instantiate(pobjPrefab, transform.position, transform.rotation);
    20.         NetworkServer.SpawnWithClientAuthority(pobj, connectionToClient);
    21.     }
    22. }
    23.  
    Can someone explain why isn't this working for me? Thanks!