You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Unity Netcode For GameObject实现主机与客户端独立相机

实现Netcode for GameObjects的3D玩家独立相机

核心逻辑很明确:仅让本地玩家的相机激活并执行跟随逻辑,远程玩家的相机直接禁用。以下是具体实现步骤:


1. 修改相机跟随脚本

在你的相机脚本中加入本地玩家判断,确保只有当前客户端控制的玩家才启用相机:

using UnityEngine;
using Unity.Netcode;

public class PlayerCamera : MonoBehaviour
{
    [SerializeField] private Transform target; // 绑定玩家的Transform
    [SerializeField] private Vector3 followOffset = new Vector3(0, 6, -12); // 可调整的相机偏移
    [SerializeField] private float smoothFollowSpeed = 0.15f;

    private void Start()
    {
        // 获取父物体的NetworkObject组件(假设相机是玩家预制体的子物体)
        NetworkObject playerNetObj = GetComponentInParent<NetworkObject>();
        
        // 非本地玩家直接禁用相机
        if (!playerNetObj.IsLocalPlayer)
        {
            gameObject.SetActive(false);
            return;
        }
        
        // 本地玩家确保相机激活
        gameObject.SetActive(true);
    }

    private void LateUpdate()
    {
        NetworkObject playerNetObj = GetComponentInParent<NetworkObject>();
        // 仅本地玩家执行跟随逻辑
        if (!playerNetObj.IsLocalPlayer) return;

        Vector3 desiredPos = target.position + followOffset;
        transform.position = Vector3.Lerp(transform.position, desiredPos, smoothFollowSpeed);
        transform.LookAt(target);
    }
}

2. 玩家预制体配置

  • 将相机作为玩家预制体的子物体,确保可以通过GetComponentInParent获取到玩家的NetworkObject组件。
  • 相机初始状态可设为激活或禁用,脚本会在Start阶段自动修正状态。

3. 额外优化方案(相机独立于预制体时)

如果相机不是玩家预制体的子物体,可通过NetworkManager的生成事件绑定本地玩家:

public class CameraManager : MonoBehaviour
{
    [SerializeField] private Camera standalonePlayerCamera;

    private void OnEnable()
    {
        NetworkManager.Singleton.SpawnManager.OnClientSpawned += BindLocalPlayerCamera;
    }

    private void OnDisable()
    {
        if (NetworkManager.Singleton != null)
        {
            NetworkManager.Singleton.SpawnManager.OnClientSpawned -= BindLocalPlayerCamera;
        }
    }

    private void BindLocalPlayerCamera(NetworkObject spawnedObj)
    {
        if (spawnedObj.IsLocalPlayer)
        {
            PlayerCamera cameraScript = standalonePlayerCamera.GetComponent<PlayerCamera>();
            cameraScript.target = spawnedObj.transform;
            standalonePlayerCamera.gameObject.SetActive(true);
        }
    }
}

注意事项

  • 禁用远程玩家的相机可避免不必要的性能消耗。
  • 测试时切换多个客户端,确认每个客户端仅显示自身控制玩家的视角。

内容的提问来源于stack exchange,提问作者Iceigloopenguin Plays

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:54:54