Unity玩家销毁后相机跟随脚本触发MissingReferenceException怎么解决
解决Unity玩家销毁后相机脚本的MissingReferenceException错误
当玩家角色被销毁后,CameraFollow和CameraClamp脚本仍在尝试访问已销毁对象的引用(比如FollowObject的Transform、Rigidbody2D),导致控制台持续输出MissingReferenceException错误。以下是具体修复方案:
修复CameraFollow脚本
在FixedUpdate方法开头添加空引用检查,如果FollowObject已为空,直接跳过后续逻辑,避免访问已销毁的对象:
修改后的完整FixedUpdate代码:
void FixedUpdate() { // 先检查FollowObject是否存在,不存在则直接返回 if (FollowObject == null) { return; } Vector2 follow = FollowObject.transform.position; float xDifference = Vector2.Distance(Vector2.right * transform.position.x, Vector2.right * follow.x); float yDifference = Vector2.Distance(Vector2.up * transform.position.y, Vector2.up * follow.y); Vector3 newPosition = transform.position; if(Mathf.Abs(xDifference) >= threshold.x) { newPosition.x = follow.x; } if(Mathf.Abs(yDifference) >= threshold.y) { newPosition.y = follow.y; } // 同时检查rb是否有效,避免访问已销毁的Rigidbody2D float moveSpeed = speed; if (rb != null) { moveSpeed = rb.velocity.magnitude > speed ? rb.velocity.magnitude : speed; } transform.position = Vector3.MoveTowards(transform.position, newPosition, moveSpeed * Time.deltaTime); }
额外优化:在Start方法中也添加空引用检查,避免初始化阶段出错:
void Start() { threshold = calculateThreshold(); if (FollowObject != null) { rb = FollowObject.GetComponent<Rigidbody2D>(); } }
修复CameraClamp脚本
根据错误提示,CameraClamp.cs第12行在Update方法中访问了已销毁的Transform,同样需要添加空引用检查:
假设脚本中存在玩家Transform的引用变量(比如playerTransform),修改Update方法:
void Update() { // 替换为你实际使用的玩家Transform变量名 if (playerTransform == null) { return; } // 原有的Update逻辑代码... }
补充说明
- 空引用检查是Unity处理对象销毁场景的标准做法,能有效避免此类运行时错误。
- 若不想销毁玩家对象,也可考虑禁用对象(调用
SetActive(false))替代销毁操作,这样引用不会失效,但需要同步调整死亡逻辑。
内容的提问来源于stack exchange,提问作者Pekovania
相关产品推荐
相关产品推荐

