ak(Clone) (UnityEngine.GameObject) 的 SpawnObject,NetworkServer 未激活。没有活动服务器无法生成对象

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

你好我正在 Unity 中制作一个对象,当玩家将鼠标悬停在它上面时会为玩家提供随机武器,但它总是给我这个警告并且没有创建它。

[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);
}

这是因为您正在从客户端调用 spawn 函数。你应该在服务器中调用它。

[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);
}

确保您从服务器和网络对象中的某些 运行 调用 spawnTime() 函数。您可以像这样过滤它:

Start(){
    NetworkIdentity nid = transform.root.GetComponent<NetworkIdentity>();

    if(nid.isServer)
    {
        spawnTime();
    }
}