• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Hathakas · Feb 05, 2015 at 05:15 AM · getcomponent

How to find child with tag?

Hey guys,

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.

 Manaliquidpriv = GetComponentInChildren<SpriteRenderer>();

Thats selecting all of the spriterenderers in the children, so I'm guessing something close to that? lol

Thanks

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Hathakas · Feb 05, 2015 at 05:29 AM 1
Share

I'm really proud of myself right now!

         $$anonymous$$analiquidpriv = GameObject.FindWithTag("Liquid Colour").gameObject.GetComponent<SpriteRenderer>();

Can't believe it worked :D

avatar image Hathakas Hathakas · Feb 05, 2015 at 05:32 AM 0
Share

Actually I just realized...this is searching all gameobjects right? So any object with the tag "Liquid Colour" :(

avatar image Hathakas · Feb 05, 2015 at 05:56 AM 0
Share

haha, thanks. :)

Is there anyway to use findwithtag with getcomponentinchildren?

5 Replies

· Add your reply
  • Sort: 
avatar image
21
Best Answer

Answer by fafase · Feb 05, 2015 at 06:46 AM

 public class Helper {
      public static T FindComponentInChildWithTag<T>(this GameObject parent, string tag)where T:Component{
           Transform t = parent.transform;
           foreach(Transform tr in t)
           {
                  if(tr.tag == tag)
                  {
                       return tr.GetComponent<T>();
                  }
           }
           return null;
     }
 }

and you use like:

 SpriteRenderer sp = parentObject.FindComponentInChildWithTag<SpriteRenderer>("LiquidColor");

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[i].CompareTag(tag) == false)
             {
                 list.RemoveAt(i);
             }
         }
         return list.ToArray();
     }
 
     public static T FindComponentInChildWithTag<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(); }
 
         T [] list = parent.GetComponentsInChildren<T>(forceActive);
         foreach(T t in list)
         {
             if (t.CompareTag(tag) == true)
             {
                 return list[i];
             }
         }
         return null;
     }
 }


Comment
Add comment · Show 15 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Hathakas · Feb 05, 2015 at 02:32 PM 1
Share

hmmm I'm confused now lol, am I supposed to change anything in the script? I'm getting an error on this line: public static T FindComponentInChildWithTag(this GameObject parent, string tag)where T:Component

"Extension must be defined in a non-generic static class"

avatar image DanSuperGP · Feb 05, 2015 at 10:11 PM 3
Share

It should be noted that this approach is several orders of magnitude faster than GameObject.Find

avatar image VOTRUBEC · Feb 06, 2015 at 02:07 AM 1
Share

Is it the "T" that you're having trouble with? If so, the format of the Extension method is including Generic types. Generics aren't constrained to Extension methods either.

As DanSuperGP says, this is much faster than doing a global search using GameObject.Find. So much so, that I'll remove my previous answer, as it doesn't apply when there's multiple objects you're searching through.

avatar image VOTRUBEC · Feb 06, 2015 at 05:26 AM 1
Share

You'd have to get rid of the generic return type T as well, and replace it with a non-generic type, or Object and then cast it.

avatar image Andergraw · Sep 13, 2017 at 11:33 AM 1
Share

This has been really helpful.

Nevertheless, if anybody else is co$$anonymous$$g over here, notice that I had to add a "return null" after the foreach in order to avoid a "not all code paths return a value" error. Thanks!

Edit: what if I want to get all children components with that tag, as we would do with "GetComponentsInChildren"?

avatar image fafase Andergraw · Sep 14, 2017 at 01:17 PM 0
Share

I edited to answer your edit comment.

avatar image Andergraw fafase · Sep 14, 2017 at 03:00 PM 0
Share

Thanks Fafase, I like the way you are managing excepctions now. On the other hand, yesterday I found this approach: what do you think about it?

 public static T[] GetComponentsInChildrenWithTag<T>(this GameObject gameObject, string tag)
         where T: Component
     {
         List<T> results = new List<T>();
 
         if(gameObject.CompareTag(tag))
             results.Add(gameObject.GetComponent<T>());
 
         foreach(Transform t in gameObject.transform)
             results.AddRange(t.gameObject.GetComponentsInChildrenWithTag<T>(tag));
 
         return results.ToArray();
     }

I took it from here:

Show more comments
Show more comments
avatar image
4

Answer by Roixo · Jan 11, 2018 at 07:38 PM

Hi, My little contribution.

If you want to find a 1st generation child GameObject by Tag:

 public static GameObject FindGameObjectInChildWithTag (GameObject parent, string tag)
     {
         Transform t = parent.transform;
 
         for (int i = 0; i < t.childCount; i++) 
         {
             if(t.GetChild(i).gameObject.tag == tag)
             {
                 return t.GetChild(i).gameObject;
             }
                 
         }
             
         return null;
     }
 
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by StephanT · May 04, 2018 at 05:22 PM

You can use LINQ:

 var renderer = GetComponentsInChildren().Where(r => r.tag == "Your Tag").ToArray()[0];

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image krupps · Apr 11, 2019 at 10:59 PM 1
Share

var renderer = GetComponentsInChildren().Where(r => r.tag == "Your Tag").FirstOrDefault(); avoids exceptions :)

avatar image olejuer krupps · Jan 03, 2020 at 08:50 AM 0
Share

shorter: var renderer = GetComponentsInChildren().FirstOrDefault(r => r.tag == "Your Tag");

avatar image
1

Answer by Developer061 · Jan 03, 2020 at 09:58 AM

The most simple one imo is to find it via ParentTransform.find("NameOfChild"); for more details, refere to https://docs.unity3d.com/ScriptReference/Transform.Find.html but i prefer if you use this, you need to do that in the start and cache it for future use.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
2

Answer by olejuer · Jan 03, 2020 at 10:58 AM

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

30 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Collection Using "GetComponent" 1 Answer

Transfering variable between gameojects and scripts 2 Answers

How to use GetComponent in a foreach loop? 3 Answers

Implicit type GetComponent call 0 Answers

How do i read the state of an enumurator on another object? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges