- Home /
Running a function on something in an area.
So I have a script attached to a grenade. the grenade has a trigger and a collider attached, I have programmed it so that when the collider touches something it runs an explode function.
The enemies all have a function LooseHealth in a script (EnemyHealthScript) , I am trying to make it so that all enemies within the tigger run the function LooseHealth(100) but I am have trouble. Right now my code for this is:
function OnTriggerStay (collision : Collider) {
if (collision.gameObject.tag == "enemy" && canExplode == true){
collision.EnemyHealthScript.LooseHealth(100);
Destroy (gameObject);
}
}
This doesnt work, I have also tried using
collision.GetComponent(EnemyHealthScript).LooseHealth(100);
but that does not work either.
Do you have any advice on how to make it work?
Answer by Bunny83 · Apr 04, 2012 at 06:01 PM
This should work:
collision.GetComponent(EnemyHealthScript).LooseHealth(100);
but your above code doesn't make sense. Are you sure you named everything correctly? the tagname? the script name? Also i'm not sure what happens if multiple objects collide with your grenade after the first one has triggered Destroy(gameObject); Maybe Unity ignores all others.
Also what exactly happens? is the grenade destroyed when canExplode is true?
Usually you would do something with Physics.OverlapSphere whenever your grenade should explode.
Your answer
