1

I'm trying to do a little bit of cleaning up and I seem to be getting the follow

NullReferenceException: Object reference not set to an instance of an object DestroyCollision.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/DestroyCollision.cs:66)

Now though, even though the entire script works perfectly (there's literally no bugs or anything) and the object reference is set correctly (since the object in question gets its active state set to false), I am stumped as to why there are any issues. The following code is the line in question:

if (collision.gameObject.tag == "Shield")
{
    GameObject.FindGameObjectWithTag("Shield").SetActive(false);
    Destroy(this.gameObject);
}

The shield object is properly tagged, and as I said, setactive(false) gets applied. Line 66 is the gameobject.find... of that line of code there.

Why am I getting the error and how to fix it?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Rick
  • 11
  • 2

1 Answers1

0

Are you sure you mean to have Destroy(this.gameObject); instead of Destroy(collision.gameObject);?

We know collision.gameObject is not null there, but you provide no info on what this.gameObject is.

Mark Cilia Vincenti
  • 1,410
  • 8
  • 25
  • Yes I do mean, sorry I realise that that part of the script wasn't completely clear, but I didn't mention it since that line doesn't affect anything (when removing it, the error still shows). The object that gets destroyed is a meteorite prefab that the script is attached to, when this collides with the shield, the shield setactive gets set to false and then the meteorite get's destroyed (therefore, this.gameobject). Hope that clarifies things a bit – Rick Nov 30 '22 at 09:36