The code now generate 100 objects at random positions.
What i want to is to make something like this structure :
Object 1
Child 1
Child 2
Child 3
Child 4
Object 2
Child 1
Child 2
Child 3
Object 3
Child 1
Child 2
Child 3
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;
private int count = 0;
// 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)
{
GameObject go = Instantiate(objectPrefab, new Vector3(Random.Range(0,10), Random.Range(0,10), Random.Range(0,10)), Quaternion.identity,parent.transform);
for(int i = 0; i < Random.Range(1,100); i++)
{
GameObject child = Instantiate(objectPrefab, new Vector3(Random.Range(0, 10), Random.Range(0, 10), Random.Range(0, 10)), Quaternion.identity, parent.transform);
go.transform.SetParent(child.transform);
}
}
count++;
if(count == 100)
{
StopAllCoroutines();
break;
}
yield return null;
}
}
}
The reason i’m using coroutine is to be able to control the spawning time.
I tried to add this part for the children part but it’s not working. it’s randomly create children but only one depth level and not for all the objects the random is seems to be random parents that get a child.
I want that each cloned prefab will have some children with unlimited random depths of levels.
for(int i = 0; i < Random.Range(1,100); i++)
{
GameObject child = Instantiate(objectPrefab, new Vector3(Random.Range(0, 10), Random.Range(0, 10), Random.Range(0, 10)), Quaternion.identity, parent.transform);
go.transform.SetParent(child.transform);
}