Home > Blockchain >  The object of type 'Transform' has been destroyed but you are still trying to access it
The object of type 'Transform' has been destroyed but you are still trying to access it

Time:10-26

MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.

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

CodePudding user response:

I think you are trying to access Transform in a particular gameobject, which is your target. But when you destroy it, for example, you can not find it anymore. The console log show that either the gameobject contain the Transform or you can not find Transform in your gameobject

CodePudding user response:

Note that target.position returns a Vector3 which is a **struct** and never can be null.

However, if the target itself was already destroyed you can't access its position!

What you want to do is rather check

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

which is using the UnityEngine.Object opreator bool

Does the object exist?

which if you like you could then also do using a ternary expression

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