It’s pretty simple to just replace Unity’s tag system with your own.
Here’s an example of how you could write a tag replacement system (to show how easy it is).
Pretty easy, and also extendable.
public class Tags : Monobehaviour
{
public string[] myTags;
bool hasTag(string tagToCheck)
{
foreach(string tag in myTags) //Can replace foreach with 'for loop'
{
if(tag == tagToCheck)
{
return true;
}
}
return false;
}
}
Alternatively you could replace the string with enum TagType
public enum TagType
{
Item,
NPC,
Player,
Object
}
//Tags.cs
public TagType[] myTags;
bool hasTag(TagType tagToCheck)
//etc.
If you want to be like Unity, you could also still use this system by simply introducing more code to do other functions, like FindGameObjectWithTag, which is much faster than GameObject.Find() because Unity stores all gameobjects with tags.
public static class TagSystem
{
public static Dictionary<string, List<Gameobject>> allTaggedGameObjects;
List<GameObject> FindObjectsWithTag(string tagToFind)
{
if(allTaggedGameObjects.ContainsKey(tagToFind)
{
return allTaggedGameObjects[tagToFind];
}
else { Debug.LogError("No Objects with Tag " + tagToFind + " found."); return null; }
}
GameObject FindObjectWithTag(string tagToFind) //Return the first tag found
{
if(allTaggedGameObjects.ContainsKey(tagToFind)
{
return allTaggedGameObjects[tagToFind][0];
}
}
static void AddGameobjectTags(Tag tagScript)
{
foreach(TagType tag in tagScript.myTags)
{
if(allTaggedGameObjects.ContainsKey(tag)
{
allTaggedGameObjects[tag].Add(tagScript.gameObject);
}
else
{
//Add new tag & new gameobject list to dictionary, etc.
}
}
}
}
//Tags.cs
void Awake()
{
TagSystem.AddGameobjectTags(this);
}
Finally, to actually get any of the tag information, you’d need a reference to the Tags.cs component.
myGameObject.GetComponent<Tags>().hasTag(theTag);
Something like that, anyway. Pretty easy stuff to simulate Unity’s tag API.
You could even extend this system to include Layers, or a third similar type. Since it’s your own custom system, it’s fully extendable for easier readability, better performance, and more overall power as a feature.
Having Enums rather than strings can save you some problems with user error (typos), among other benefits. It’s up to you though. It’ll all perform extremely fast, so readability is most important.
Note: I’m not an expert, so I’m always open to improvement. I’d love for anyone who believes this is inefficient, to comment as to why (I’m trying to build a collection of solid ‘best practices’ or ‘systems’ which users could find & use.) so I can explain any caveats.
<p>i have a strange solution for you, check here:-</p> <p><a href="http://blockmonkey.com/my-work/unity-3d-work/" rel="nofollow">http://blockmonkey.com/my-work/unity-3d-work/</a></p> <p>it's a script that allows you to put in Multiple tags on an object...</p>
– anon86749518