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
}

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("

“, System.Array.ConvertAll(values, v => " public 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.