简体   繁体   中英

How can i get in array or List all the child gameobjects under a gameobject?

In the top of the script:

public CameraControl cameraControl;
public Object birdPrefab;
public Transform birdParent;
private Transform cameraObj;
public Transform[] instancePoints;
public int _birdscount;
private Settings res;

Then in this function

private GameObject InstantiateBird( Vector3 position, Quaternion rotation, Boid.Settings boidSettings )
  {
    var obj = (GameObject)Instantiate( birdPrefab, position, rotation );
    var boid = obj.GetComponent<Boid>();

    obj.transform.parent = birdParent;
    boid.SettingsRef = boidSettings;
    boid.DebugSettingsRef = settings.debugSettings;

    return obj;
  }

And then in the function i want to get all the childs:

int prevBirdCount;
    IEnumerator _WatchBirdCount()
    {
        prevBirdCount = _birdscount;

        while(true)
        {
            if(_birdscount != prevBirdCount)
            {
                prevBirdCount = _birdscount;
                //Do something
                foreach (Transform child in birdPrefab)
                {
                    //child is your child transform
                }
                InstantiateBirds();
            }
            yield return 0; //Wait a frame before checking again
            {
            }
        }
    }

But the foreach is wrong: foreach (Transform child in birdPrefab)

This is a screenshot showing the hierarchy while the game is running and the inspector of the main camera on the right.

You can see in the Hierarchy under BirdsParent i want to get all the HumanBirdPrefab(Clone) in a List and then to do something with them.

In the inspector you can see in the Main (Script) the Bird Prefab and Bird Parent.

屏幕截图

Now I could be wrong but in that foreach, you can't use the gameObject, you need to use a transform, so either do

foreach (Transform child in birdPrefab.transform){}

or if birdParent is the transform of the birdPrefab, do this

foreach (Transform child in birdParent){}

This error message is useful and should have been added to the question: Assets\\Scripts\\Main.cs(5,5): Error CS1579: foreach statement cannot operate on variables of type 'UnityEngine.Object' because 'UnityEngine.Object' does not contain a public definition for 'GetEnumerator' (CS1579) (Assembly-CSharp)

You are doing nothing in that foreach : there's just a comment, inside. You should add child.gameObject to the list at each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM