Help with for loop 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!


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;

In your Instantiate you are trying to get an item from cardSpots by generating a random number which is between 0 and length of cards array. So since your cards array has length larger than cardSpots you are getting that error. Your Instantiate statement should be:

Instantiate(cardSpots[Random.Range(0, cardSpots.Length)], cardSpots*.transform.position, Quaternion.identity);*

In the line

Instantiate(cardSpots[Random.Range(0, cards.Length)], cardSpots*.transform.position, Quaternion.identity);*

You are basing the index you’re getting in Random.Range(0, card.Length) off of the cards array, not the cardSpots array. This wouldn’t be problematic if both arrays had the same number of items in them, but clearly they have a different number of items.
Is your intention to get a GameObject from cards or from cardSpots? Make sure you’re only basing your index off of the right array’s length, not a different one.
For example:
Instantiate(cardSpots[Random.Range(0, cardSpots.Length)], cardSpots*.transform.position, Quaternion.identity);*
Instantiate(cards[Random.Range(0, cards.Length)], cardSpots*.transform.position, Quaternion.identity);*
A really good way to stop confusion with variables is to more properly describe what they’re doing. For example, if you’re variable is intended to be a collection of Prefabs - not just game objects - call it CardPrefabs instead of just Cards, et cetera.

Random.Range(0, cards.Length) does not include the 0 but does include the cards.Length I think that makes it go out of bounds.

You can do

int i = Random.Range(0,cards.Length);


from the Unity manual
Note that max is inclusive, so using Random.Range( 0.0f, 1.0f ) could return 1.0 as a value.