- Home /
How to I make FindGameObjectWithTag() not just find itself?
I am trying to make a system where a type of enemy only attacks when it is in a group, and runs away when no other enemies are near by. I'm trying to do this by using tags, but the scripts keeps just finding itself, so it always thinks that there is another enemy with it. This is the code I'm using to identify close by enemies:
void Update()
{
friendly = GameObject.FindGameObjectWithTag("Enemy").transform;
{
If anyone could revise my system or find a better way of doing this it would be much appreciated.
Answer by derfium · Apr 15, 2020 at 08:19 AM
You could just use FindGameObjectsWithTag()
instead of looking for a single GameObject.
void Update()
{
GameObject[] friendly = GameObject.FindGameObjectsWithTag("Enemy");
if (friendly.Length > 1) {
DoSomething();
} else {
DoSomethingElse();
}
}
You can find the Reference here.
But I would advice you to not do that. Every GameObject.Find()
-Method will just iterate over all GameObejcts in the hierarchy. Doing that every single frame, say 60+ times a second will definitely slow down your game.
Instead, you could create a list and add your enemies to that list once you Instantiate them. When they die and you destroy their GameObject, just remove them from the list. To check how many enemies are still alive just check the list's length with enemies.Count`. Enemies will be a list of Enemies, as in List enemies = new List();
If you don't have a Enemy Script, just make it a list of GameObjects or Transforms.