Array index is out of range.
Hello i have almost finished my 2D mobile game but i have a very last issue stepping in my way that i can't figure out the solution so i'm hoping that someone could help me. Here is the code:
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class collectDimonds : MonoBehaviour {
public static int dimonds = 0;
public int dimondValue = 1;
public Transform[] dimondSpawn;
public Image dimond;
public bool spawning = false;
// Use this for initialization
void Start () {
dimonds = PlayerPrefs.GetInt ("Dimanti");
}
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.tag == "Dimond")
{
dimonds += dimondValue;
Destroy(coll.gameObject);
spawning = false;
}
}
void Update()
{
PlayerPrefs.SetInt("Dimanti", dimonds);
if (!spawning) {
Spawn();
}
}
void Spawn ()
{
spawning = true;
Transform coinSpawns = dimondSpawn [Random.Range (0, dimondSpawn.Length)];
Image coinPrefab = (Image)Instantiate (dimond, coinSpawns.position, coinSpawns.rotation);
coinPrefab.transform.SetParent(GameObject.FindObjectOfType<Canvas>().gameObject.transform);
}
}
And the error says:
IndexOutOfRangeException: Array index is out of range. collectDimonds.Spawn() (at Assets/scripts/collectDimonds.cs :54)
probably because dimondSpawn.Length
is one too many.
you should move the PlayerPrefs.SetInt()
to the trigger code - there's no need to set it every frame if it hasn't changed.
however, it's difficult to say whether that's even needed - are you using PlayerPrefs
to share values between scripts? it's generally used to store value between game sessions...
So i moved PlayerPrefs.SetInt() to the trigger code, but i still can't figure out the error
Answer by EmHuynh · Feb 15, 2016 at 04:47 AM
Hello, @Bondolero!
The problem is in this line: Transform coinSpawns = dimondSpawn [Random.Range (0, dimondSpawn.Length)];
The max range of Random.Range
should be the length of array dimondSpawn
subtracted by 1. Because you want the the last index of dimondSpawn
.
So this should work: Transform coinSpawns = dimondSpawn [Random.Range (0, dimondSpawn.Length - 1)];
Here's a sample:
int[] intArray = new int[ 3 ] { 2, 4, 6 };
void Update()
{
// Invalid. Error: IndexOutOfRangeException:
// Array is out of range.
Debug.Log( intArray[ intArray.Length ] );
// Valid. Length of array subtracted by 1.
Debug.Log( intArray[ intArray.Length - 1 ] );
}