How do I check if an object is null?

I am making a game where enemies chase their target by moving towards them and rotating their gun towards them, but whenever the player is destroyed I get this error:

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.

This is the rotate gun script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class rotateEnemyGun : MonoBehaviour
{
public float offset;
public Transform player;

// Update is called once per frame
void Update()
{
    if (player != null)
    {
        Vector2 playerPos = player.transform.position;
        Vector2 lookPos = playerPos - (Vector2)transform.position;
        float rotZ = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;

        transform.rotation = Quaternion.AngleAxis(rotZ - offset, Vector3.forward);
    }
}

}

6 Answers

6

It could be the following reason, but not 100% sure:

You are checking if the player is “null”. But you are deleting the player. So the player is not “null” it just has a “missing reference” (you should be able to see it in the inspector). So you should maybe set the player manually to “null” before destroying it.

I hope it works :slight_smile:

How would I do that?

Have you tried if (player) instead of if (player != null) ?

Yeah, but it didn't work either.

does we place this at the parent ?

I don’t see any issues with the code you’ve posted. Are you sure the error is in this script? The code you’ve posted can’t really be the cause of the error you’ve mentioned.

There is no error in the script, the error is that when the player gets destroyed by the bullets from the enemy, it is trying to find the non existing player, but it can't find it, so it gives the error 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.

You just need to reference the parent transform and you can use this on any script

Don’t destroy the player, just disable it.

I might try that

I know this comment was a year ago, but how exactly do I disable it. I'm running into the exact same issue, but I can't quite find a Disable command. Thank you!

Just check:

if(player.gameobject != null){do stuff}

So if you destroy the gameobject, or just the script or renderer or whatever, there’s a chance, that the transform exists and your testing the transform. But if your’re if the gameobject is null, it definitly should work.

@Jasic560 Try `If (player = null) {

return

}`

that might fix it

I've already tried that, it didn't work.