Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GameObject.FindGameObjectsWithTag() not working

I am trying to find all game objects with the tag "Guard". For some reason, this is not working. I have tried it with other tags, and I know there are objects with the tag "Guard".

My Code

GameObject[] guards;

void Start()
{
    guards = GameObject.FindGameObjectsWithTag("Guard");
    print(guards + name);
}

I know this is probably really simple, but printing it always results in a empty array. I am a Unity beginner, and would really appreciate the help. Thank you! :)

like image 953
NullAndVoid21 Avatar asked Feb 01 '26 13:02

NullAndVoid21


1 Answers

How do you know it's empty?

If your opinion is based on print output, then you are wrong. Print will always throw just a type of guards variable and a name of gameObject to which this script is attached to. If you want to check the number of gameObjects found, you should use guards.Length or make a variable public so that you have a peek at it from the Inspector on runtime.

public GameObject[] guards;

void Start ()
{
    guards = GameObject.FindGameObjectsWithTag("Guard");
    print(guards.Length);
}
like image 63
Nikola G. Avatar answered Feb 04 '26 03:02

Nikola G.