- Home /
need help with C# component reference
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!
Have you used Debug.Log(other.name);
to make sure other
is what you're expecting?
Answer by Burla · May 03, 2014 at 02:39 PM
Assuming that the DestroyBox takes a GameObject parameter you could do it this way.
Declare the BoxDestruction variable at the top of your script.
BoxDestruction boxDestruction;
Make the reference in the Start function.
void Start() {
boxDestruction = GetComponent<BoxDestruction>();
}
Now call the function.
void OnTriggerStay2D (Collider2D other)
{
if(other.tag == "Destructible")
{
if(destroyBox)
boxDestruction.DestroyBox(other.gameObject);
}
}
Your answer
Follow this Question
Related Questions
Asset bundles and scene references 1 Answer
Losing reference to monobehaviour after updating a dll 0 Answers
Multiple DLL with the same class reference 1 Answer
Using DestroyImmediate on one GameObject makes a reference to another a null 1 Answer
Retain references to child gameobjects while duplicating objects 0 Answers