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

}

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:

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

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.

Don’t destroy the player, just disable it.

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