- Home /
How to access tags to avoid strig literals
Hey All
I am wondering if there is a way to programatically get the tags in the editor rather than comparing them using a string like the following example :
if (other.gameObject.CompareTag("Coconut")) { //Do stuff }
Answer by Hellium · May 21 at 11:51 AM
There is no built-in way to do so unfortunately, but you can generate a class at compile time:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class TagAndLayerProcessor
{
static TagAndLayerProcessor()
{
AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
}
private static void OnBeforeAssemblyReload()
{
CreateClass("Tags", UnityEditorInternal.InternalEditorUtility.tags);
CreateClass("Layers", UnityEditorInternal.InternalEditorUtility.layers);
}
private static void CreateClass(string className, string[] values)
{
string content = string.Join("\n", System.Array.ConvertAll(values, v => $"\tpublic const string {ObjectNames.NicifyVariableName(v).Replace(" ", "")} = \"{v}\";"));
System.IO.File.WriteAllText(Application.dataPath + $"/Scripts/{className}.cs", string.Format(Format, className, content));
}
private const string Format = @"public static class {0}
{{
{1}
}}";
}
The script will create a new Layers & Tags file for you. Example of output:
public static class Layers
{
public const string Default = "Default";
public const string TransparentFX = "TransparentFX";
public const string IgnoreRaycast = "Ignore Raycast";
public const string Water = "Water";
public const string UI = "UI";
}
Note that you'll probably need to make the project compile twice in order for this to work if you ever add/remove tags/layers.
You could also go with a MenuItem instead, but you'll have to manually trigger the option.
Your answer
Follow this Question
Related Questions
C# change an object tag wit raycasthit. 2 Answers
Change something in this script 2 Answers
Assigning tag on runtime break loop in C# unity3D 4.3. 1 Answer
Changed Prefab tag Still objects untagged?? 4 Answers
How do I tag a question as solved? 1 Answer