Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
0
Question by CiberX15 · Aug 10, 2013 at 06:00 PM · transformgetcomponentchildren

How to get all children gameobjects

Ok I have seen this asked a few times but I have not seen a satisfactory answer. I have a space ship that is made up of a bunch of game objects that are all parented to a "command seat" game object. These objects all have a script that holds variables like thrust and power consumption. I want the command chair to have a function that iterates through all of its children and adds up all of the variables to be used to calculate the ships total thrust and such. The reason I am doing it this way instead of simply setting these values on the command chair is that the parts that make up the ship can be destroyed. When this happens the function that tallied up all the variables would be run again to get the new variables. This way if you blow up the ships engines it actually gets slower.

Problem is, unity seems to have a hard time actually getting children game objects. I have tried this code:

 function CompileShip()
 {
     for(var child in transform)
     {
         //child is your child transform
         Debug.Log(child);
         
         var moduleThrust = child.GetComponent(ModuleScript).Thrust;
     }
 }

it does return the child transforms, but I have no idea how to access the gameobject, or the components from that. The last line "var moduleThrust = child.GetComponent(ModuleScript).Thrust;" does not work, it was more of an example of what I would like to do.

So again, the core issue here is getting information out of the script component of the children. But I was only aware of the "getComponent()" method. If there is some way to get the gameobject out of the transform, or if there is a way to get the script components please let me know.

Thanks in advance to anyone who can help.

Comment
Add comment · Show 2
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 CiberX15 · Aug 10, 2013 at 09:02 PM 0
Share

This doesn't even make sense. Why can't I get the children of an object directly. Why do I have to do this backwards get transform then try to get a game object from it. Isn't a transform the location, rotation and scale of an object? I mean the way this is set up it is almost as if the programmers never expected anyone to possibly need to access anything else [insert dripping sarcasm here].

avatar image cregox · Nov 05, 2013 at 04:11 PM 0
Share

duplicate http://answers.unity3d.com/questions/205391/how-to-get-list-of-child-game-objects.html

5 Replies

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

Answer by CiberX15 · Aug 10, 2013 at 11:42 PM

Ok well this works:

 function CompileShip()
 {
 
     var allChildren = gameObject.GetComponentsInChildren(Transform);
     
     for (var child : Transform in allChildren) 
     {
         // do whatever with child transform here
         var Module : GameObject = child.gameObject;
         var childStats : ModuleScript;
         
         childStats = Module.GetComponent(ModuleScript);
         if(childStats != null)
         {
             Debug.Log(Module);
             //TODO add up all the variables from the children
         }
     }
 }

I still think it is a rather round about way of getting what I want, and it generates an implicit downcast warning but it works. If anyone figures out a better way of doing this please post it, otherwise I guess this is how it's done.

Comment
Add comment · Show 5 · 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 Joyrider · Aug 11, 2013 at 12:18 AM 0
Share

A specific reason you are first getting the transforms and then your specific component, ins$$anonymous$$d of getting your specific component directly?

avatar image Linus · Aug 11, 2013 at 12:18 AM 0
Share

GetComponetsInChildren returns Component not Transform. Its rather backwards I agree.

You could use pragma downcast http://forum.unity3d.com/threads/63114-What-is-pragma-implicit-and-pragma-downcast to get rid of the warning at least.

I did find a solution here on answers once that was better. Ill post if I find it again

avatar image cregox · Nov 05, 2013 at 04:09 PM 0
Share

It's my impression that using for (var child in transform) is much faster.

avatar image whydoidoit · Nov 05, 2013 at 04:37 PM 0
Share

But that only gets the first level of children.

avatar image cregox · Nov 05, 2013 at 04:40 PM 0
Share

So true. But still, on my brief test, I only had the first level...

avatar image
0

Answer by Jamora · Aug 10, 2013 at 06:05 PM

You can access the GameObject a transform belongs to with .gameObject. To access the gameobjects of all your child transforms, you'd need

 var moduleThrust = child.gameObject.GetComponent(ModuleScript).Thrust;

EDIT: If you use inheritance, or happen to have the same script you need to get from each child, you could also use GetComponentsInChildren to find all the thrust-adding types and then just iterate over the array to get the total thrust. Something along the lines of Thrust[] modules = gameObject.GetComponentsInChildren(); from your command seat gameobject.

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 CiberX15 · Aug 10, 2013 at 06:35 PM 0
Share

I tried that, it returns an error : 'gameObject' is not a member of 'object'. (BCE0019)

avatar image cregox · Nov 05, 2013 at 04:08 PM 0
Share

You probably tried that line without a foreach, @CiberX15

avatar image
0

Answer by whydoidoit · Aug 10, 2013 at 10:30 PM

So presuming you have a Thrust script attached to every game object that provides Thrust (and might therefore be destroyed) and this has a Value (for the thrust) you can sum them like this:

     import System.Linq;

     ...

     var totalThrust = GetComponentsInChildren.<Thrust>().Aggregate(0f, function(current, thrust) current + thrust.Value);
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 Linus · Aug 11, 2013 at 12:45 AM

 for (t in transform.GetComponentsInChildren.<Transform>()) {
     Debug.Log('child name'+t.name);
 }


As mentioned I had seen a topic on this here at answers. But I could not find it again. It probably suggested this. It does not give any error and works with pragma strict.

I would use it like this:

 #pragma strict
 import System.Collections.Generic;
 
 //Find all modules, and store them in a generic list
 // See http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use? for information on usage of Generic List
 var shipModules : List.<ModuleScript> = new List.<ModuleScript>();
 
 function Start () {
     
     for (m  in transform.GetComponentsInChildren.<ModuleScript>()) {
         shipModules.Add(m);
     }
 
 }
 
 
 
 function GetTotalThrust(){
     var totalThrust : float;
     
     for(m in shipModules){
         totalThrust += m.Thrust;
     }
     
     return totalThrust;
 }
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 g4tobauer · Apr 28, 2015 at 03:19 AM

 Component[] cps = gameObject.GetComponentsInChildren<Component>();
 
 foreach (Component cp in cps)
 {
    print(cp.gameObject.name);
 }


use this...

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

20 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

Related Questions

Accessing children of instances vs children of original prefab 1 Answer

How Should I Get a List of Child Objects 2 Answers

Getting transform info after branch 1 Answer

modifing enemies target inside a radius 1 Answer

How getting transform of another GameObject C#? 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