How to instantiate a random object from an array?

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:

void Update ()
  {
     if (Input.GetKeyDown ("down")) {
        Instantiate (pieces[Random.Range(0,pieces.Length)], spawnLocation.position, spawnLocation.rotation);
  }
}

Get rid of “FindObjectWithTag”. It will be always return null because the GameObject you want to “FIND” is not in the “game” already.

Jus use this code

     public Transform spawnLocation;
     
     public GameObject[] pieces;
 
     void Update (){

if (Input.GetKeyDown ("down")) {
 
Instantiate (pieces[UnityEngine.Random.Range(0,6)], spawnLocation.position, spawnLocation.rotation);
}

}

In the inspector, put how many GameObject you prefer to choose to instantiate. then Drag the gameobjects in the inspector.

Make all of initial in Start()

void Start()
{
         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");
}