Create Tags by Script in Unity


Júlio Rodrigues ·

Tags are wonderful, and you want to set up several of them in an automatic way for your editor scripts. But how could this be achieved? There seems to be no reference to this API in the manual. It's a little odd but possible.

Welcome to the AssetDatabase

Tags can't be accessed directly since there's no specialized API for them, but nonetheless, it's possible to change and create them accessing the asset data of your project directly. It's a bit clumsy because this API needs to be generic enough to work for all use cases.

It's reserved for more specialized use cases, like this one. Whenever you want to access or modify assets you should use the AssetDatabase instead of working with the filesystem directly since Unity has to keep track of changes of the projects directory.

The AssetDatabase interface is only available in the editor, it doesn't have any function on a final game build.

Accessing the Tag Manager

In the next section, there's a full sample on how to access and modify the Tag Manager asset, but the idea is this:

  1. Load the asset file "ProjectSettings/TagManager.asset" and keep a reference to it
  2. Interface with it using a SerializedObject
  3. Do changes
  4. Save those changes

All this is done inside an editor script.

As all editor scripts, it must be contained in a directory called Editor. Anywhere in the Assets folder will do it, you just need to create a folder called Editor and put your editor scripts inside it.

Adding a Tag & SerializedObjects

To add a tag it's necessary to deal directly with the unity representation of their serialized system. Serialization is a big and hot topic in Unity, explaining it is out of the scope of this article, but if you really want to understand what's going on in the following example you'll need to understand how the engine handles serialization, you can get started by watching this excellent presentation by Richard Fine on Unity Europe 2017.

But you can still do it without understanding how it works in its entirety. The calls we are going to do are the creation of the SerializedObject object, FindProperty, some array manipulations and a couple methods to update the serialized object in the database. It's as if we were working as programming language implementers, this is meta-y functionality.

Here's a sample editor script that creates random tags, you can adapt it to your own needs.

Assets/Editor/TagsCreatorWindow.cs
using System;
using System.Text;
using UnityEngine;
using UnityEditor;

public class TagsCreatorWindow : EditorWindow {

 public static void CreateTag(string tag) {
  var asset = AssetDatabase.LoadMainAssetAtPath("ProjectSettings/TagManager.asset");
  if (asset != null) { // sanity checking
   var so = new SerializedObject(asset);
   var tags = so.FindProperty("tags");

   var numTags = tags.arraySize;
   // do not create duplicates
   for (int i = 0; i < numTags; i++) {
    var existingTag = tags.GetArrayElementAtIndex(i);
    if (existingTag.stringValue == tag) return;
   }

   tags.InsertArrayElementAtIndex(numTags);
   tags.GetArrayElementAtIndex(numTags).stringValue = tag;
   so.ApplyModifiedProperties();
   so.Update();
  }
 }

 [MenuItem("Window/Tags Creator")]
 public static void ShowWindow() {
  EditorWindow.GetWindow(typeof(TagsCreatorWindow));
 }

 string RandomString() {
  StringBuilder sb = new StringBuilder();
  const string glyphs = "ABCHDJWYUEQOPO0457894";
  int len = UnityEngine.Random.Range(7, 10);
  while (len-- > 0) {
   sb.Append(glyphs[UnityEngine.Random.Range(0, glyphs.Length)]);
  }
  return sb.ToString();
 }

 void OnGUI() {
  if (GUILayout.Button("Create Random Tag")) {
   CreateTag(RandomString());
  }
 }
}

It definitely looks Hacky

Since it's done only in editor-time, even if it stops being compatible, you'll won't end with a broken build that's unfixable. Whenever a new version of Unity breaks this, you'll be able to fix it and continue to use your editor script as usual.

And during run-time, while the game is running?

Unfortunately, it seems to be impossible to create tags after the build is closed.

You're are now able to create tags in your editor scripts, what are you going to do with this new power? Let me know on [email protected]. You can also follow me to make any further questions or to get to know about the new articles first.


Classify in:
  • scripting
  • tags
  • extending the editor
© Bladecast 2018. All rights reserved.