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

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;
    }
  }

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");