- Home /
calling a function from a script on a collsion object
on collision I want to call the function SpawnDefender() from the script SummonDefenderOnStand() . I am doing this by finding the gameObject of the collider and then using GetComponent to find the script and it's function. However it does not find the function SpawnDefender().
Thanks in advance for any help.
private GameObject defenderStand;
if (other.tag == "defenderStand")
{
defenderStand = other.gameObject.GetComponent<GameObject>();
defenderStand.GetComponent<SummonDefenderOnObject>().SpawnDefender();
defenderStand.SpawnDefender();
}
Answer by doublemax · Jan 27, 2017 at 12:52 AM
Try this:
if (other.tag == "defenderStand")
{
SummonDefenderOnObject defenderStand = other.gameObject.GetComponent<SummonDefenderOnObject>();
if( defenderStand )
defenderStand.SpawnDefender();
}
Converted into an answer.
@bstout:
Feel free to accept his answer if your question is answered.
I would like to add that whenever comparing tags ins$$anonymous$$d of doing other.tag == "some tag"
, try this other.CompareTag(some tag)
. It is much more efficient and does not produce garbage for garbage collector.
Your answer
![](https://koobas.hobune.stream/wayback/20220612105657im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unable to access function in different script 1 Answer
Collison Sphere / Tagged Enemies only Near Player selection 0 Answers
How to get a character controller to interact with rigidbodies with C# 0 Answers
Can't get onCollisionStay() to work for me 2 Answers
Start function is getting called twiced 0 Answers