Search Unity

[SOLVED] Find all childs with rigidbody component ?

Discussion in 'Scripting' started by Quast, Jan 9, 2020.

  1. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    560
    Hi.


    I'm trying to find all childs with rigibody component and add it to array.
    I don't know how to find them ?
    Code (CSharp):
    1.  
    2.  
    3.     public GameObject [] Ragdoll;
    4.     public GameObject Hip;
    5.  
    6.     void Start()
    7.     {
    8.        
    9.         Ragdoll = new GameObject [Hip.transform.childCount]; // It counts only first 3 objects !!?
    10.  
    11.         for (int p = 0; p < Hip.transform.childCount; p++)
    12.         {
    13.             print("p "+ p);
    14.         //    Ragdoll[p] = Hip.transform.GetChild(p).gameObject;
    15.  
    16.         }
    17.  
    18.  
    19.     }
    20.  
    21.  
     
  2. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    You can get all of the components first:
    Code (csharp):
    1. List<Rigidbody> bodies = GetComponentsInChildren<Rigidbody>();
    2. Ragdoll = new GameObject[bodies.Count];
    3. for(int i = 0; i < bodies.Count; i++)
    4.    Ragdoll[i] = bodies[i].gameObject;
     
  3. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    560
    It gives me this error with first line
     
  4. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Opps, I forgot that it returned an array instead of a collection. Change the list to an array, and use .Length instead of .Count.
     
    Quast likes this.
  5. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    560
    Good. Thank you so much WallaceT.