【问题标题】:The object of type 'Transform' has been destroyed but you are still trying to access it'Transform' 类型的对象已被销毁,但您仍在尝试访问它
【发布时间】:2021-10-24 23:23:32
【问题描述】:

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);
        }
    }
}

【问题讨论】:

  • 谁破坏了目标?

标签: unity3d camera destroy


【解决方案1】:

我认为您正在尝试访问特定游戏对象中的 Transform,这是您的目标。但是,例如,当您销毁它时,您将无法再找到它。控制台日志显示游戏对象包含变换,或者您在游戏对象中找不到变换

【讨论】:

  • 我从 if (target.position != null) 中删除 .position 并且它的工作
【解决方案2】:

注意target.position 返回一个Vector3,它是一个**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 opreator bool

对象是否存在?

如果您愿意,也可以使用 ternary 表达式来实现

transform.position = target ? Vector3.Lerp(transform.position, target.position + offset, smoothSpeed) : Vector2.zero;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多