Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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
2
Question by NhommeBeurreOne · Jul 16, 2012 at 04:03 PM · javascriptgameobjecttagfindgameobjectswithtag

Find child of a Game Object using tag

Hello,

So I have a Game Object in my scene with 4 child. I want to put the 4 child in a GameObject[]. I have this code :

var other : GameObject;
var gos2 : GameObject[];
gos2 = other.FindGameObjectsWithTag("Cover Node");

Instead of listing the 4 child of other(Game Object) it list all the game objects with the tag Cover Node. Do you have any solution?

Have A Nice Day
NbO

Comment
Add comment
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

4 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by Piflik · Jul 16, 2012 at 08:12 PM

Try something like this. It is an edited part of a script that I (successfully) use in my game (I look for only one item and don't store it in an array).

 for(var child : Transform in transform){
     if(child.gameObject.tag == "Cover Node"){
         gos2.Add(child);
     }
 }

(As it is now, the script has to be attached to the parent of the objects. If you want to have this script on an unrelated object, you'd have to write 'for(var child : Transform in other.transform)', where other is the same variable you use in the script you posted)

Comment
Add comment · Show 11 · 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 NhommeBeurreOne · Jul 16, 2012 at 08:31 PM 0
Share

It's telling that Add it's not a part of Unity GameObject[]

avatar image Piflik · Jul 16, 2012 at 08:39 PM 0
Share

Oh....right...'Add()' doesn't work with the builtin arrays...let's try again ;)

 var tempcounter : int = 0;
 for(var child : Transform in transform){
     if(child.gameObject.tag == "Cover Node"){
         gos2[tempcounter] = child;
         tempcounter++;
     }
 }
avatar image NhommeBeurreOne · Jul 16, 2012 at 08:48 PM 0
Share

Cannot convert 'UnityEngine.Transform' to 'UnityEngine.GameObject'. It seems that child is a Transform am I right?

avatar image Bovine · Jul 16, 2012 at 08:50 PM 0
Share

gos2[tempcounter] = child.gameObject;

avatar image NhommeBeurreOne · Jul 16, 2012 at 08:54 PM 0
Share

IndexOutOfRangeException: Array index is out of range. (wrapper stelemref) object:stelemref (object,intptr,object) PrototypeCoverSystemAI.FindBestCoverNode () (at Assets/PrototypeCoverSystemAI.js:37) PrototypeCoverSystemAI.Update () (at Assets/PrototypeCoverSystemAI.js:11) ;)

Show more comments
avatar image
1

Answer by delstrega · Jul 16, 2012 at 04:14 PM

This should return all child GameObjects of a given object (even deactivated ones):

 function GetChildGameObjects(theParent : GameObject) : GameObject[]{
  var tempTransforms : Transform[];
  tempTransforms = theParent.GetComponentsInChildren(Transform, true);
  
  var children: GameObject[] = new GameObject[tempTransforms.length-1];
  
  for(var i=0; i < tempTransforms.length-1; i++){
     children[i] = tempTransforms[i+1].gameObject;
  }
  return children;
 }

Use it like this:

 gos2 = GetChildGameObjects(other);

EDIT: Just remembered that GetComponentsInChildren returns the parent too, so I adjusted the code accordingly to only return the children, excluding the parent.

Comment
Add comment · Show 11 · 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 NhommeBeurreOne · Jul 16, 2012 at 04:19 PM 0
Share

Thank you for the fast feedback let me try it and accept your answer as correct one.

avatar image NhommeBeurreOne · Jul 16, 2012 at 06:42 PM 0
Share

Get This : Assets/PrototypeCoverSystemAI.js(12,13): BCE0017: The best overload for the method 'PrototypeCoverSystemAI.test(UnityEngine.GameObject)' is not compatible with the argument list '()'.

avatar image fafase · Jul 16, 2012 at 07:17 PM 0
Share

It is not related to the code he gave you. The error tells you provided the wrong parameter to the method PrototypeCoverSystemAI.test().

avatar image NhommeBeurreOne · Jul 16, 2012 at 07:50 PM 0
Share

Do you have any idea what the problem could be?

avatar image Bovine · Jul 16, 2012 at 08:00 PM 0
Share

it's worth noting that you don't want to be doing this sort of searching very often. It's the sort of thing you might do at startup, but don't do it every frame!

If, as suggested by your question, you're looking for nodes for AI to run to, you might want to cache the node somehow or arrange them so they can be easily found.

For instance: add triggers to your cover objects and at the point the AI decides it needs to find cover, you could do an overlap sphere or cast to deter$$anonymous$$e where the nearest bit of cover is. You'd do this once, cache the result and then manage the business of dashing over to the cover. You could put AI stuff on an AINodes layer and limit your overlap or cast to that layer, speeding it up.

I'm pretty sure the above will be quicker, although a desktop machine might not grumble at it too much. It's still a good idea to follow this approach.

Show more comments
avatar image
1

Answer by siddharth3322 · Aug 27, 2014 at 03:35 AM

Here is C# code for similar.

 private List<GameObject> spawnPoints = new List<GameObject>();
 
     void Start(){
         PrepareSpawnPointList();
     }
 
 private void PrepareSpawnPointList(){
         foreach(Transform child in transform){
             if(child.CompareTag(GameConstants.TAG_SPAWN_POINT))
                 spawnPoints.Add(child.gameObject);
         }
     }

You directly use this code for your purpose.

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
0

Answer by Dune2 · Sep 30, 2016 at 02:18 PM

If you're using C#, and you want to find within nested children, then you may find either of the following extensions helpful.

 using UnityEngine;
 using System.Linq;
 using System.Collections.Generic;
 
 public static class TransformExtensions
 {
     /// <summary>
     /// Find all children of the Transform by tag (includes self)
     /// </summary>
     /// <param name="transform"></param>
     /// <param name="tags"></param>
     /// <returns></returns>
     public static List<Transform> FindChildrenByTag(this Transform transform, params string[] tags)
     {
         List<Transform> list = new List<Transform>();
         foreach (var tran in transform.Cast<Transform>().ToList())
             list.AddRange(tran.FindChildrenByTag(tags)); // recursively check children
         if (tags.Any(tag => tag == transform.tag))
             list.Add(transform); // we matched, add this transform
         return list;
     }
 
     /// <summary>
     /// Find all children of the GameObject by tag (includes self)
     /// </summary>
     /// <param name="gameObject"></param>
     /// <param name="tags"></param>
     /// <returns></returns>
     public static List<GameObject> FindChildrenByTag(this GameObject gameObject, params string[] tags)
     {
         return FindChildrenByTag(gameObject.transform, tags)
             //.Cast<GameObject>() // Can't use Cast here :(
             .Select(tran => tran.gameObject)
             .Where(gameOb => gameOb != null)
             .ToList();
     }
 }
 

You would in the OP's case use it like.

 var other : GameObject;
 var gos2 : GameObject[]; 
 gos2 = other.FindChildrenByTag("Cover Node").ToArray();
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.

Follow this Question

Answers Answers and Comments

11 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

Related Questions

Destroy gameobject by tag (.js) 3 Answers

Find the first game object created with a given name 1 Answer

lookAt nearest object to another object 1 Answer

Hit any gameobject, animation will play? 1 Answer

GameObject.findGameObjectsWithTag returning empty? 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