Unity报MissingReferenceException:Transform已销毁仍被访问如何解决
Unity相机跟随MissingReferenceException异常解决方案
报错原因
- 原代码的空校验逻辑完全错误:你校验的是
target.position != null,但position是Vector3值类型,值类型不存在null的可能,该判断永远返回true,else分支永远不会触发 - 异常触发的核心逻辑:当你绑定的跟随目标(例如玩家对象)被销毁后,
target这个Transform引用本身已经为空,代码执行到访问target.position时,相当于对空引用读取属性,直接触发MissingReferenceException
修复方案
将空校验的对象改为target本身,先确认target存在后再访问它的属性,修正后的代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { public Transform target; public float smoothSpeed = 0.125f; public Vector3 offset; void LateUpdate() { // 先校验target本身是否存在 if (target != null) { Vector3 desiredPosition = target.position + offset; Vector3 smoothPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed); transform.position = smoothPosition; } else { // 修正了原逻辑赋值Vector2丢失Z轴的问题,避免相机和场景同层导致渲染异常 transform.position = new Vector3(0, 0, transform.position.z); // 可选优化:如果需要自动重新寻找跟随目标,可取消下方注释,将Player改为你目标的对应标签即可 // var newTarget = GameObject.FindGameObjectWithTag("Player"); // if (newTarget != null) target = newTarget.transform; } } }
内容的提问来源于stack exchange,提问作者joe
相关产品推荐
相关产品推荐

