按键控制Cinemachine Tracked Dolly沿路径移动,脚本组件无法赋值
解决Unity Cinemachine Tracked Dolly组件无法赋值及相机航点移动问题
一、组件赋值失败的排查与解决
- 确认组件类型:检查你的CinemachineVirtualCamera上挂载的是
CinemachineTrackedDolly组件,不是类似的CinemachineDollyCart模块,两者功能不同,别搞混。 - 手动赋值规范:如果脚本挂在VirtualCamera对象上,直接拖自身的Tracked Dolly组件到字段;如果脚本在其他对象,要拖VirtualCamera上的对应组件,别选错对象。
- 自动获取组件兜底:如果手动赋值始终显示
None,在脚本的Start()方法里自动获取组件,避免人为操作失误:void Start() { // 脚本挂在VirtualCamera上时,直接获取自身组件 if (dolly == null) dolly = GetComponent<CinemachineTrackedDolly>(); // 脚本挂在其他对象时,先找到VirtualCamera再获取 // dolly = GameObject.Find("你的VirtualCamera名称").GetComponent<CinemachineTrackedDolly>(); }
二、Input System按键逻辑优化
原代码的移动逻辑过于生硬(单次加1),且方法名与功能不符,调整为平滑移动并匹配按键功能:
using UnityEngine; using Cinemachine; using UnityEngine.InputSystem; public class DollyCameraController : MonoBehaviour { public CinemachineTrackedDolly dolly; // 可调整的移动速度,适配不同长度的航点路径 public float moveSpeed = 0.1f; void Start() { // 自动兜底获取组件 if (dolly == null) dolly = GetComponent<CinemachineTrackedDolly>(); } // 绑定W键:沿航点前进 public void OnDollyForward(InputAction.CallbackContext context) { // 持续按住按键时触发平滑移动 if (context.performed) dolly.m_PathPosition += moveSpeed * Time.deltaTime; } // 绑定E键:沿航点后退 public void OnDollyBackward(InputAction.CallbackContext context) { if (context.performed) dolly.m_PathPosition -= moveSpeed * Time.deltaTime; } }
三、额外注意事项
- 确保CinemachineVirtualCamera的
Follow和Look At目标设置正确,否则移动时可能出现偏移或旋转异常。 - 控制
m_PathPosition的取值范围,超出航点路径的首尾节点范围可能导致相机位置异常。 - 检查Input System的Action绑定:在Input Actions资产中,将W/E键分别关联到
OnDollyForward和OnDollyBackward方法,确保触发逻辑生效。
内容的提问来源于stack exchange,提问作者NectarNoks
相关产品推荐
相关产品推荐

