【问题标题】:How would I spawn a different prefab for a local client and a remote client in Unity with MLAPI?如何使用 MLAPI 在 Unity 中为本地客户端和远程客户端生成不同的预制件?
【发布时间】:2021-11-12 00:21:44
【问题描述】:

对不起,如果这是一个重复的问题。

我发现这个 Reddit 帖子正是我当前的问题。 https://www.reddit.com/r/Unity2D/comments/lw96s5/multiplayer_cameras/

但是,只有一条评论不是描述性的,并且没有任何指向“教程”的链接。换句话说,我在 Unity 中有一个 MLAPI 游戏,带有 LocalPlayer 预制件(有摄像头、FPS 移动代码和 PlayerInput)和 ServerPlayer(没有摄像头或 PlayerInput 组件)预制件。它们代表我游戏中不同的复制玩家。

当前的问题是决定是生成本地玩家还是远程玩家的代码。

决定生成什么预制件:

        private void ApprovalCheck(byte[] connectionData, ulong clientId, MLAPI.NetworkManager.ConnectionApprovedDelegate callback)
        {
            //Your logic here
            bool approve = connectionData == System.Text.Encoding.ASCII.GetBytes("xd");
            bool createPlayerObject = true;

            if (NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject.IsLocalPlayer)
            {
                localPlayerPrefab.GetComponent<NetworkObject>()
                .SpawnAsPlayerObject(clientId);
            }
            else
            {
                serverPlayerPrefab.GetComponent<NetworkObject>()
                .SpawnAsPlayerObject(clientId);
            }


            //If approve is true, the connection gets added. If it's false. The client gets 
            disconnected
            callback(createPlayerObject, null, approve, positionToSpawnAt, Quaternion.identity);
        }

如果您需要任何额外的详细信息,请告诉我。

【问题讨论】:

  • 使用相同的预制件,而不是让预制件本身检查它是否属于本地播放器。如果是,请保持相机处于活动状态,否则停用/销毁它...
  • @derHugo 这不起作用。 playerCamera.transform.parent.gameObject.GetComponent&lt;NetworkObject&gt;().IsLocalPlayer
  • 我应该使用NetworkBehaviourIsLocalPlayer吗?

标签: c# unity3d p2p multiplayer unity3d-unet


【解决方案1】:

如前所述,我认为您应该始终为所有玩家生成相同的预制件,而不是拥有像例如这样的组件

public class LocalPlayerControl : NetworkBehaviour 
{
    void Start()
    {
        if (IsLocalPlayer) return;

        var cam = GetComponentInChildren<Camera>();
        
        cam.enabled = false;
        // or a bit more radical
        Destroy(cam);
        // or if your cam is on a sub object with additional components (e.g. usually AudioListener etc)
        Destroy(cam.gameObject);

        // same for all other components that you don't want a remote player to have
    }

【讨论】:

  • 当我加入主机(在同一台计算机上)时,它会立即破坏我的相机。
猜你喜欢
  • 1970-01-01
  • 2021-08-14
  • 2021-11-01
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多