I have several copies of a box prefab that has the following components:
“BoxColider2D”,
“RigidBody2D”,
“Sprite Renderer” & a custom C# script called “BoxDestruction”.
I also have a “Danger Zone” object which has a BoxCollider2D with isTrigger enabled. I want to destroy boxes that are inside the “Danger Zone” trigger at random intervals (when the destroyBox bool is true).
I am using the following code on the “Dander Zone” trigger to try and call the public DestroyBox() function in the “BoxDestrction” script of the box which is inside the trigger. I am getting a NullReferenceException: Object reference not set to an instance of an object, but i cannot tell why? i thought that starting from “other” would give me the instance of the object i am after?
void OnTriggerStay2D (Collider2D other)
{
if(other.tag == "Destructible")
{
if(destroyBox)
other.gameObject.GetComponent<BoxDestruction>().DestroyBox();
}
}
Can anyone tell me what i am doing wrong when trying to reference this? i would really appreciate an explanation, as i can’t see where i am going wrong…
Thanks in advance!