- Home /
How to make the other gameObject carry out a function.
I'm making a game where a projectile can hit several things. Depending on the tag, the object that would hit would have a function activated by the projectile. I'm also planning of having several enemies with the same scripts and I don't want to affect all of their scripts at once, but just the ones that are hit, similar to Game Maker's "other" function.
How would you say "other" in this situation?
function OnTriggerEnter(collision : Collider){
if(collision.gameObject.tag == "Enemy"){
/*?other?*/takeDamage();
}
}
Answer by AyAMrau · Jul 11, 2014 at 02:13 PM
You need to get the script (component) on the enemy that has the takeDamage function (Check out the documentation here)
collision.gameObject.GetComponent(NameOfTheScriptOnEnemyObject).takeDamage();
Obviously replace the name in () to whatever your script containing takeDamage()
is called.
Answer by AdamAndersson · Jul 11, 2014 at 02:26 PM
Hello!
If I understand you correctly you might try to get all the MonoBehaviour components of the gameObject and then use the name of the MonoBehaviour to determine which MonoBehaviour you want to call. Try do something like this inside the if-statement above:
// Get all MonoBehaviours attched to this game object
MonoBehaviour[] monoBehaviours = collision.gameObject.GetComponents<MonoBehaviour>();
foreach(MonoBehaviour script in monoBehaviours)
{
if(script.name == "ScriptName") // If this is the script you want to call (rename 'ScriptName' to the actual name of your script)
{
script.Invoke("takeDamage",0); // Call othe object's function
}
}
Your answer
Follow this Question
Related Questions
Physics.OverlapSphere() not working after using pool of objects 0 Answers
My marble (Player/Gameobject) goes through the "play board" (gameobject). Why? 1 Answer
Enemy Detects Buildings? 2 Answers
Multiple Enemy Collision Help 0 Answers
Is there any way to convert Collision to a Gameobject or Transform? 1 Answer