Hello, i’m newbie in unity. I want to fill an list like 4X5 or 5x4 with gems but not instantly smthing like 1 gem per second and when 4X5 is complete stop falling. this is my code. How can i do this?
public class List : MonoBehaviour {
public GameObject gem;
public List<GameObject> gems = new List<GameObject>();
// Use this for initialization
void Start () {
for (int y=0; y<5; y++) {
for (int x=0; x<4; x++) {
// GameObject g =Instantiate(gem, new Vector3(x, y, 0), Quaternion.identity) as GameObject;
// gems.Add(g);
}
}
}
// Update is called once per frame
void Update () {
Vector3 fall = new Vector3 (1,2,0);
gems.Add((GameObject)Instantiate(gem, fall, Quaternion.identity));
}
}
Two issues first: Please format code questions! Select the code you’re pasting, and press the 0101 button.
Secondly, you shouldn’t name your class “List”, as there’s already a built-in class named “List”, and that’ll end up causing confusion.
Now, to solve your problem, the easiest thing would be to use a Coroutine. In essence, they’re methods that you can pause for a certain amount of time (or until an event is finished). You can read about them here.
Your code would be:
public class GemThingy : MonoBehaviour {
public GameObject gem;
public List<GameObject> gems = new List<GameObject>();
bool finishedSpawning;
void Start() {
StartCoroutine(SpawnCoroutine());
}
private IEnumerator SpawnCoroutine() {
finishedSpawning = false;
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 4; x++) {
GameObject g = Instantiate(gem, new Vector3(x, y, 0), Quaternion.identity) as GameObject;
gems.Add(g);
//Wait for a second before continuing the for-loop
yield return new WaitForSeconds(1f);
}
}
finishedSpawning = true;
}
void Update() {
if (!finishedSpawning)
return;
//Make the gems fall
}