Checking for null

Hi guys

So I am getting the following error below.

MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it.Your script should either check if it is null or you should not destroy the object.

The error message is pointing the below code…

void updateCameraPosition()
    {
        if( !_playerController )
        {

            transform.position = Vector3.SmoothDamp( transform.position, target.position - cameraOffset, ref _smoothDampVelocity, smoothDampTime );
            return;
       

        }

On this exact line

transform.position = Vector3.SmoothDamp( transform.position, target.position - cameraOffset, ref _smoothDampVelocity, smoothDampTime );

So basically my gameObject gets destroyed and this part of the code is still accessing it. I would like to be checking for null I have tried the following below with no luck.

if( !_playerController )

if( _playerController == null)
if( _playerController != null)

Does someone have a better way around this? or to stop it from accessing my gameObject?

Thank you

As a MonoBehaviour gets destroyed, OnDisable and OnDestroy are called. You need to make sure that at least after OnDestroy was called, you are not anymore calling updateCameraPosition.

1 Like

Hi,
Are you sure that you used Destroy? not DestroyImmediately?

That’s my death script I am using, yeah I just use Destory.

var isDead = false;
var death : AudioClip;
function OnGUI()
{
    if (isDead)
    {
        GUI.Box(Rect(630, 100, 270, 250), "You're dead");
        if(GUI.Button(Rect(640,150,250,100), "Try Again"))
        {
            Application.LoadLevel("JacksJacketendless");
            isDead = false;
           
        }
    }
}
function OnCollisionEnter2D(jack : Collision2D)
{
    if (gameObject != null )
    {   
        Destroy(jack.gameObject);
    }
    isDead = true;
}

Ok. what does it , target.position? in your scripy maybe that is null and you have to check if it is not null?

It’s targeting my character, the script makes his gameObject get destroyed.

but the code Is still updating. not sure how to check if it is not null, :S

void updateCameraPosition()
    {
        if( !_playerController )
        {
            transform.position = Vector3.SmoothDamp( transform.position, target.position - cameraOffset, ref _smoothDampVelocity, smoothDampTime );
            return;

just check if(target != null)

1 Like

Awesome, that is the one thank you very much DiRe! You are a champ!

Cheers mate :smile: