- Home /
Question by
Hiiro27 · Jul 20, 2016 at 08:55 PM ·
c#getcomponentfindgameobjectswithtag
how i can Get component in FindGameObjectsWithTag ???
I want to getcomponent from a lot of enemy, if just 1 enemy :
GameObject enemy;
enemyScript EnemyScript;
void Start ()
{
enemy = GameObject.FindGameObjectWithTag ("enemy");
EnemyScript = enemy.GetComponent <enemyScript > ();
}
But i need more enemy, so how i can use FindGameObjectWithTag??
public GameObject [] enemy;
enemyScript EScript;
void Start ()
{
GameObject[] enemy = GameObject.FindGameObjectsWithTag ("Ghoul");
EScipt = enemy.GetComponent<enemyScript> ();
//This is wrong, but how i can make it better,,
}
Comment
Best Answer
Answer by btmedia14 · Jul 20, 2016 at 10:23 PM
Once you have the array, probably looking to just loop through them:
void Start ()
{
GameObject[] enemy = GameObject.FindGameObjectsWithTag ("Ghoul");
foreach(GameObject oneEnemy in enemy)
{
Escript = oneEnemy.GetComponent<enemyScript> ();
// do something with Escript etc
}
}
Answer by rodude123 · Apr 28, 2020 at 02:42 PM
I know this answer is a bit late but a more update to answer to this could be something like this which is fewer lines of code but don't know if this is the most efficient way to do this.
List<enemyScript> players = GameObject.FindGameObjectsWithTag("Ghoul").Select(obj => obj.GetComponent<enemyScript>()).ToList();
Your answer
![](https://koobas.hobune.stream/wayback/20220612085200im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Getcomponent error? 1 Answer
Accesing components on multiple objects in c#? 2 Answers
GetComponent sometimes doesn't work 1 Answer