Wait until a key is pressed inside a loop
hi, i'm a little new in unity and can do basic things with c# and i have a question. I have a script that instantiates a blockPrefab to one of the 8 spawnPoints. Then there are cubePrefab that are instantiated in front of the blockPrefab. For example, if the BlockPrefab is instantiated at spawnPoint 3 then a cubePrefab is instantiated at spawnPoint 2 and a second at spawnPoint 1 and so on until spawnPoint 0. But I want the cubePrefab to be instantiated one after the other when the user presses the button "space". In the previous example the user will have to press the "space" button 3 times to instantiate the 3 cubePrefab. But in my code the script does not wait for me to click the button "space" and generate blockPrefab without stopping ... So to recap my script works fine and does what I want. Except that I would like the cubePrefab spawn only if I click on "space" and the code waits before continuing. Do you have an idea? thank you a lot
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class montagneSpawner : MonoBehaviour
{
private int randomIndex;
public Transform[] spawnPoints; // spawnPoints for blockPrefab
public GameObject blockPrefab;
public Transform[] cubeSpawnPoints; //spawnpoints for cubePrefab
public GameObject cubePrefab;
void Update()
{
SpawnBlocks();
}
void SpawnBlocks()
{
int randomIndex = Random.Range(0, spawnPoints.Length); // choose a spawnPoint position
Instantiate(blockPrefab, spawnPoints[randomIndex].position, Quaternion.identity); //instantiate blockPrefab to one of the 8 spawnPoints
//instantitate cubePrefab
for (int i = 0; i != randomIndex+1; i++)
{
// if (Input.GetKeyDown("space")) I tried this if statement but it didn't wait that I pressed the "space" and instantiate only the blockPrefab
//{
Instantiate(cubePrefab, cubeSpawnPoints[i].position, Quaternion.identity);//instantiate cubePrefab until all spawnPoint are full
// }
}
}
}
Answer by AaronXRDev · Aug 06, 2019 at 02:51 PM
In your Update put this:
if(Input.GetKeyDown(KeyCode.Space))
{
SpawnBlocks();
}
Also, for more information on the Input system, go to: https://docs.unity3d.com/ScriptReference/Input.html
Your answer
Follow this Question
Related Questions
How to get a for loop to run once per coroutine? 0 Answers
Cross with cubes using for? 0 Answers
If statement in for loop not working after fail 0 Answers
How to get a for loop to run once per coroutine? 1 Answer
Can't Locate gameobject in array 3 Answers