Search code examples
unity-game-enginenetwork-programminggame-enginemultiplayerunity3d-mirror

SpawnObject for ak(Clone) (UnityEngine.GameObject), NetworkServer is not active. Cannot spawn objects without an active server


helloI'm making an object in Unity that gives players random weapons when they hover over it, but it always gives me this warning and doesn't create it.

[ClientRpc]
public void spawnTime()
{
    StartCoroutine(spawn());
}
public IEnumerator spawn()
{
    Debug.Log("oldu");
    yield return new WaitForSeconds(1);
    int a = Random.Range(0, guns.Length);
    GameObject gun =Instantiate(guns[a], spawnPoint.position,Quaternion.identity);
    gun.transform.SetParent(transform);
    NetworkServer.Spawn(gun);
}

Solution

  • This is because of you are calling the spawn function from client. You should call it in server.

    [Server]
    public void spawnTime()
    {
        StartCoroutine(spawn());
    }
    
    [Server]
    public IEnumerator spawn()
    {
        Debug.Log("oldu");
        yield return new WaitForSeconds(1);
        int a = Random.Range(0, guns.Length);
        GameObject gun =Instantiate(guns[a], 
        spawnPoint.position,Quaternion.identity);
        gun.transform.SetParent(transform);
        NetworkServer.Spawn(gun);
    
    
        uint gunNetId = gun.GetComponent<NetworkIdentity>().netId;
        uint parentNetId = transform.root.GetComponent<NetworkIdentity>().netId;
        RpcSetParent(parentNetId, gunNetId);
    }
    
    [ClientRpc]
    void RpcSetParent(uint parentNetId, uint childNetId)
    {
        Transform child = NetworkClient.spawned[childNetId].transform;
        Transform parent = NetworkClient.spawned[parentNetId].transform;
    
        child.SetParent(parent);
    }
    

    Be sure that you are calling the spawnTime() function from something running in server and networked object. You can filter it something like:

    Start(){
        NetworkIdentity nid = transform.root.GetComponent<NetworkIdentity>();
    
        if(nid.isServer)
        {
            spawnTime();
        }
    }