MissingReferenceException: 'Transform' 型別的物件已被銷毀,但您仍在嘗試訪問它。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
// Update is called once per frame
void LateUpdate()
{
if (target.position != null)
{
Vector3 desiredPosition = target.position offset;
Vector3 smoothPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothPosition;
}
else
{
transform.position = new Vector2(0, 0);
}
}
}
uj5u.com熱心網友回復:
我認為您正在嘗試訪問特定游戲物件中的 Transform,這是您的目標。但是,例如,當您銷毀它時,您將無法再找到它。控制臺日志顯示游戲物件包含變換,或者您在游戲物件中找不到變換
uj5u.com熱心網友回復:
請注意,target.position回傳 aVector3是 a**struct**并且永遠不能是null。
但是,如果它target本身已經被銷毀,您將無法訪問它的位置!
你想做的是檢查
if(target)
{
Vector3 desiredPosition = target.position offset;
Vector3 smoothPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothPosition;
}
else
{
transform.position = new Vector2(0, 0);
}
這是使用UnityEngine.Object運算子bool
物件是否存在?
如果你愿意,你也可以使用三元運算式
transform.position = target ? Vector3.Lerp(transform.position, target.position offset, smoothSpeed) : Vector2.zero;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/336652.html
下一篇:找到玩家右側/左側
