Skip to content

Instantly share code, notes, and snippets.

@immrsv
Created November 3, 2020 01:45
Show Gist options
  • Save immrsv/6d319f31e2dc8c926e0fb9872298a5d2 to your computer and use it in GitHub Desktop.
Save immrsv/6d319f31e2dc8c926e0fb9872298a5d2 to your computer and use it in GitHub Desktop.
Custom multi-tag for Unity
[DisallowMultipleComponent]
public class DynamicTag : MonoBehaviour
{
private static Dictionary<string, List<GameObject>> Collection = new Dictionary<string, List<GameObject>>();
private static string KeyFromTag(DynamicTagItem tag) {
return tag.name;
}
public static void Register(DynamicTagItem tag, GameObject item) {
var key = KeyFromTag(tag);
if (!Collection.ContainsKey(key))
Collection.Add(key, new List<GameObject>());
Collection[key].Add(item);
}
public static void Deregister(DynamicTagItem tag, GameObject item) {
var key = KeyFromTag(tag);
if (!Collection.ContainsKey(key))
return; // No Such Tag
// In case of multiple entries, remove all occurences of item
// If you're sure you will only have one entry per item, you can just use 'Remove'
Collection[key].RemoveAll(m => m == item);
}
public static IEnumerable<GameObject> FindObjectsWithTag(DynamicTagItem tag) {
var key = KeyFromTag(tag);
if (!Collection.ContainsKey(key))
return null;
return Collection[key].AsEnumerable();
}
public DynamicTagItem[] Tags;
private void Awake() {
foreach (var tag in Tags)
Register(tag, gameObject);
}
private void OnDestroy() {
foreach ( var tag in Tags)
Deregister(tag, gameObject);
}
}
[CreateAssetMenu(fileName ="DynamicTag", menuName ="Scriptables/CustomTag")]
public class DynamicTagItem : ScriptableObject { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment