index out of range problem with for loops and arrays.

Hello so i have a script that is suppose to spawn a card at a random cardSpot. So i tried to get all objects from an array in this case the cardSpots. And then check if the cardspots bool ‘isFree’ is true. Then i spawn a random card from an other array at that chosen cardspots position. But i get an error that says ‘Index out of range’ i checked the script and everything seems to be fine. Would be glad if someone could tell me what the issue is and why. Im sorry if it’s really easy im new to loops and arrays! Anyhow thanks!

Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Deck : MonoBehaviour {

	public GameObject[] cards;
	public GameObject[] cardSpots;

	public void GiveCard ()
	{
		Debug.Log ("function worked");

		for (int i = 0; i < cardSpots.Length; i++)
		{
			if (cardSpots *.GetComponent<Spot> ().isFree == true)*
  •  	{*
    

_ Instantiate(cardSpots[Random.Range(0, cards.Length)], cardSpots*.transform.position, Quaternion.identity);_
_ cardSpots .GetComponent ().isFree = false;
return;
}
}
}
}*_

Hi.

You seem to instantiate from the cardSpot array on line 18. I think you want to instantiate a card from the cards array. Other than that; Random.Range is max inclusive meaning you could risk still hitting outside of the array. Do Random.Range(0, cards.Length - 1) instead

Tip: On line 16, doing if (cardSpots_.GetComponent().isFree == true) is the same as not checking with true, so: if (cardSpots*.GetComponent().isFree).*_
Also i would recommend that the cardSpot array is an array of Spot instead of gameObject. This would reduce the amount of getComponent calls.