'How to Instantiate prefab clone and each clone to have random number of children of children?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GenerateObjects : MonoBehaviour
{
    public GameObject objectPrefab;

    [Range(1, 100)]
    public int numberOfObjects = 1;

    private GameObject parent;

    // Start is called before the first frame update
    void Start()
    {
        parent = GameObject.Find("Generate Objects");

        StartCoroutine(SpawnObjects());
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator SpawnObjects()
    {
        while (true)
        {
            yield return new WaitForSeconds(0);

            if (objectPrefab != null)
            {
                Instantiate(objectPrefab, new Vector3(Random.Range(0,10), Random.Range(0,10), Random.Range(0,10)), Quaternion.identity,parent.transform);
            }
           
            yield return null;
        }
    }
}

now it's generating random objects. i want it also to generate for each clone of the prefab and random number of childs and random childs of childs with unlimited depth of children of children. it can be very nested.

The idea in the end is that each clone of the prefab will have some children some with only children and some with more depth levels. the goal is to make the tree of children randomly.



Solution 1:[1]

I need to use Transform.childCount, Transform.GetChild and Transform.SetParent. Also you need to stop your coroutine, of not it'll run forever. Not debugged draft for the first children hierarchy of private GameObject parent:

IEnumerator SpawnObjects() {
    for (int i=0; i<parent.childCount;i++) {
        Transfrom parentGo = parent.transform.GetChild(i);
        GameObject instantiatedGO = Instantiate(objectPrefab, new Vector3(Random.Range(0,10), Random.Range(0,10), Random.Range(0,10)), Quaternion.identity,parent.transform);
        instantiatedGO.transform.SetParent(parentGo);
    }
}

Also check the coroutine documentation. The execution of a coroutine can be paused at any point using the yield statement. When a yield statement is used, the coroutine pauses execution and automatically resumes at the next frame, so if you do not what to handle the stop of it, or need some frame or time related operation, you can execute it without the yield statement. That leads the question of if you need the coroutine at all. If not, why then not just call the method directly without a coroutine. Thats for you to decide.

With what you've got already and the documentation you should be able to achieve it :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1