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

Unity3D FollowCam跟随相机无法自动跟随动态生成的玩家载具

解决方案

方案原理

你当前的问题根源是动态生成载具后,AutoCam的跟随目标参数没有被自动赋值,之前的预制体打包方案虽然可用,但存在资源冗余、维护成本高的问题,更规范的方案通过代码在载具生成后自动为AutoCam组件赋值跟随目标,无需将相机和载具绑定。

步骤1:为AutoCam添加公共目标设置接口

Unity官方标准资源允许自定义修改,你可以直接在AutoCam类中新增目标赋值方法,避免直接暴露私有字段:

namespace UnityStandardAssets.Cameras
{
    public class AutoCam : PivotBasedCameraRig
    {
        // 原有代码保持不变,新增以下方法
        public void SetFollowTarget(Transform target)
        {
            m_Target = target;
            // 可选:重置相机状态,避免切换载具时出现转场异常
            m_CurrentTurnAmount = 1f;
            m_RollUp = Vector3.up;
        }
    }
}

步骤2:修改载具加载代码自动绑定目标

修改LoadCharacter类,新增AutoCam引用字段,载具生成后自动调用上述接口赋值目标:

public class LoadCharacter : MonoBehaviour
{
    public GameObject[] characterPrefabs;
    public Transform spawnPoint;
    // 新增字段,在Inspector中拖入场景里的AutoCam组件即可
    public AutoCam mainFollowCam;

    void Start()
    {
        int selectedCharacter = PlayerPrefs.GetInt("selectedCharacter");
        GameObject prefab = characterPrefabs[selectedCharacter];
        GameObject clone = Instantiate(prefab, spawnPoint.position, Quaternion.identity);
        // 自动绑定跟随目标
        mainFollowCam.SetFollowTarget(clone.transform);
    }
}

替代实现(无需手动拖引用)

如果不想在Inspector中手动赋值AutoCam引用,小项目可以直接用FindObjectOfType查找场景中的AutoCam实例:

void Start()
{
    int selectedCharacter = PlayerPrefs.GetInt("selectedCharacter");
    GameObject prefab = characterPrefabs[selectedCharacter];
    GameObject clone = Instantiate(prefab, spawnPoint.position, Quaternion.identity);
    // 自动查找场景中的AutoCam组件
    AutoCam cam = FindObjectOfType<AutoCam>();
    if(cam != null)
    {
        cam.SetFollowTarget(clone.transform);
    }
}

注意事项

  • 确保所有载具预制体都挂载了Rigidbody组件,AutoCam内部需要读取目标的刚体速度参数
  • 如果场景中存在多个相机,建议给主跟随相机添加唯一标签,通过GameObject.FindWithTag查找更精准

内容的提问来源于stack exchange,提问作者Mariana Cristina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 14:15:04