I am trying to make a Tetris clone for practice but i cannot get my objects to spawn randomly. I’m still a noob to this any help would be greatly appreciate.
public int pieceSpawn;
public GameObject linePiece;
public Transform spawnLocation;
public GameObject[] pieces;
void Update ()
{
pieces = new GameObject[7];
pieces[0]=GameObject.FindGameObjectWithTag("cube");
pieces[1]=GameObject.FindGameObjectWithTag("line");
pieces[2]=GameObject.FindGameObjectWithTag("L");
pieces[3]=GameObject.FindGameObjectWithTag("J");
pieces[4]=GameObject.FindGameObjectWithTag("s");
pieces[5]=GameObject.FindGameObjectWithTag("Z");
pieces[6]=GameObject.FindGameObjectWithTag("T");
pieceSpawn = UnityEngine.Random.Range (0,7);
if (Input.GetKeyDown ("down")) {
Instantiate (pieces[UnityEngine.Random.Range(0,6)], spawnLocation.position, spawnLocation.rotation);
I would recommend that you create a prefab for each GameObject (Drag each Gameobject from the Hierarchy somewhere into the Project panel). Then assign all of them to the pieces array in the inspector (Drag them onto the name and they’ll add up). This will also reduce the possibility of making a mistake. THEN, you can shorten your code and make it bulletproof: