I have a gameobject with 5 children, they all have spriterenderers. I need to access one of them with the tag (Liquid Color) but I can’t seem to find a simple way. It does’t really have to be through tag I suppose, name is fine too.
Edit: what if I want to get all children components with that tag, as we would do with “GetComponentsInChildren”?
public static class Helper
{
public static T[] FindComponentsInChildrenWithTag<T>(this GameObject parent, string tag, bool forceActive = false) where T : Component
{
if(parent == null) { throw new System.ArgumentNullException(); }
if(string.IsNullOrEmpty(tag) == true) { throw new System.ArgumentNullException(); }
List<T> list = new List<T>(parent.GetComponentsInChildren<T>(forceActive));
if(list.Count == 0) { return null; }
for(int i = list.Count - 1; i >= 0; i--)
{
if (list*.CompareTag(tag) == false)*
{ list.RemoveAt(i); } } return list.ToArray(); }
public static T FindComponentInChildWithTag(this GameObject parent, string tag, bool forceActive = false) where T : Component { if (parent == null) { throw new System.ArgumentNullException(); } if (string.IsNullOrEmpty(tag) == true) { throw new System.ArgumentNullException(); }
T [] list = parent.GetComponentsInChildren(forceActive); foreach(T t in list) { if (t.CompareTag(tag) == true) { return list*;* } } return null; } }
In these situations, I would consider creating a new MonoBehaviour Script and put it on your object you are looking for. You can use empty MonoBehaviours to tag things and then find them with GetComponentsInChildren. This is more flexible than tags and names, because you can have multiple of these components on any object. Actually, by the name “tag” this is what you would intuitively expect tags to be like. Yes, you have to create those scripts, but that’s really simple. You can create as many components as you need, while there is a finite amount of tags for some reason. Also components can hold additional data.
This kinda goes in the direction of DOTS.
Often times you don’t even need to look up those objects when your dedicated component can handle whatever needs to be done to the object.