I am trying to run a c# script onto a Person object and expected to show 10 clones at random locations, however only showed 1.
Here is Population Manager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PopulationManager : MonoBehaviour {
public GameObject personPrefab;
public int populationSize = 10;
List<GameObject> population = new List<GameObject>();
public static float elapsed = 0;
// Use this for initialization
void Start () {
Vector3 pos = new Vector3(Random.Range(-9, 9), Random.Range(-4.5f, 4.5f), 0);
GameObject go = Instantiate(personPrefab, pos, Quaternion.identity);
go.GetComponent<DNA>().r = Random.Range(0.0f, 1.0f);
go.GetComponent<DNA>().g = Random.Range(0.0f, 1.0f);
go.GetComponent<DNA>().b = Random.Range(0.0f, 1.0f);
population.Add(go);
}
// Update is called once per frame
void Update () {
}
}
How could I fix this issue?
The reason why it’s creating a single clone is because the code is creating only a single object. Put the code to create clones inside a loop like this.
void Start () {
for(int i = 0; i < 10; i++){
Vector3 pos = new Vector3(Random.Range(-9, 9), Random.Range(-4.5f, 4.5f), 0);
GameObject go = Instantiate(personPrefab, pos, Quaternion.identity);
go.GetComponent<DNA>().r = Random.Range(0.0f, 1.0f);
go.GetComponent<DNA>().g = Random.Range(0.0f, 1.0f);
go.GetComponent<DNA>().b = Random.Range(0.0f, 1.0f);
population.Add(go);
}
}