- Home /
How to check if a tag exists?
Hey Everyone,
Im using
GameObject.FindGameObjectsWithTag()
to get a list of objects that have that specific tag, however not every tag used as input is a valid tag, it's a string that can be edited in the editor. I expected
FindGameObjectsWithTag
to return an empty array when there's no object found with a tag (which would be the case if the tag is not even defined) but instead I get this error message:
UnityException: Tag: is not defined.
It seems that it does not compute that method because the tag does not exists, the tag used to trigger this error is an empty string, I'm not sure if there's any difference between "" or string.Empty but it was the value unity uses when a public string is left blank in the inspector.
Is it possible to check if a tag exists or to get a list of strings of all tags set in the unity project? After browsing the forum I found a post from 2012 from someone who had a similar problem and fixed it by using an editor script. In my case however, it also needs to work on runtime so I can not use the editor script.
Kind regards,
Yorick van de Haar
Answer by Nischo · Feb 22, 2017 at 02:14 PM
Something like this should work, while still being horrible style, and should not be called frequently
public static bool DoesTagExist(this GameObject aObj, string aTag)
{
try
{
aObj.FindGameObjectsWithTag(aTag);
return true;
}
finally
{
return false;
}
}
I made it an extension method so you can call DoesTagExist on any game object.
bool doesIt = myGameObject.DoesTagExist("Player");
Thank you very much! The try/catch exception handling statement did the trick!
Answer by thornebrandt · Jan 09, 2020 at 02:21 AM
The accepted answer wasn't working for me but I changed it slightly.
public static bool DoesTagExist(string aTag)
{
try
{
GameObject.FindGameObjectsWithTag(aTag);
return true;
}
catch
{
return false;
}
}
Good variant in the Bad situation of absent correct method.
Little correction - changed "FindGameGame Objects()" on "FindGameGame Object()" . It will be more simple
The accepted answer should work but has done it as an extension method, so you need a GameObject to call it on, which is redundant and unnecessarily complicated.
So yes, yours looks better to me.