Created
November 3, 2020 01:45
-
-
Save immrsv/6d319f31e2dc8c926e0fb9872298a5d2 to your computer and use it in GitHub Desktop.
Custom multi-tag for Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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