我小时候把Hand Prefab固定在Player Prefab上。 我想在Hand Prefab(玩家子代)中生成Gun Prefab。 这样可以从Hand级别做到这一点吗?
此刻,我正在从Hand生成Gun,但它仅适用于单个Player。当我和2个玩家一起玩时,会产生一把枪。客户端游戏崩溃。这是我收到的错误消息:
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)
HandHolder.CmdGetGun () (at Assets/Scripts/HandHolder.cs:27)
HandHolder.Update () (at Assets/Scripts/HandHolder.cs:19)
多数民众赞成在我手上:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class HandHolder : NetworkBehaviour {
[SerializeField] GameObject gun;
private GameObject playerGun;
// Update is called once per frame
void Update () {
if(GetComponentInParent<NetworkIdentity>().isLocalPlayer)
{
if (playerGun)
{
playerGun.transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z - 1);
playerGun.transform.rotation = transform.rotation;
}
else if (Input.GetKeyDown(KeyCode.I))
{enter code here
CmdGetGun();
}
}
}
// [Command]
public void CmdGetGun()
{
playerGun = Instantiate(gun, transform.position, transform.rotation) as GameObject;
NetworkServer.SpawnWithClientAuthority(playerGun, GetComponentInParent<NetworkIdentity>().connectionToClient);
}
}
我在CmdGetGun()方法之前添加[Command]时,在生成枪支的瞬间出现了以下错误消息:
There is no NetworkIdentity on this object. Please add one.
UnityEngine.Networking.NetworkBehaviour:get_isServer()
HandHolder:CallCmdGetGun()
HandHolder:Update() (at Assets/Scripts/HandHolder.cs:19)
但是,当我将NetworkIdentity添加到我的孩子Hand Prefab中时,它向我显示hasAuthority,对于Hand和Player来说,isLocalPlayer均为False。
我不知道如何在手工预制件中生成Gun。
这是组件和树:
答案 0 :(得分:0)
您的网络对象是播放器,因此您需要通过播放器路由网络功能。
在播放器类中调用CmdGetGun()*并从那里调用它。
* CmdGetGun()不应为[Command]
(可选)您可以将CmdGetGun作为命令来调用,但是然后您就不需要网络化的实例化,而只是本地的(该命令将被称为所有客户端,因此所有客户端都将在本地创建枪支。)
编辑
CmdGetGun将在所有客户端上创建对象,但不会像您期望的那样将其作为父对象。您可能应该尝试我提到的第二种方法(将其称为命令,但是在本地实例化)