Index Out of Range problem

Hello, I’m sorry for asking but I have a problem with the following script. I don’t know why but when I start the game I’ve got “IndexOutOfRangeException : Arrat index is out of range” error. So I know it came from my array but as I do not have define any range or length I don’t know why I’ve got this message.

Is there someone who know how can I solve this ?

Thanks so much

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

using System.Linq;
using System.Text;
using System.IO;

public class CreationPlanetes : MonoBehaviour {

    public GameObject PlaneteTerreObjet;
    public GameObject PlaneteMarsObjet;
    public GameObject PlaneteMercureObjet;
    public GameObject PlaneteJupiterObjet;
    public GameObject PlaneteVenusObjet;

    public GameObject[] TabPlanete;

    private float tempo1 = 0.0f; 
    public static int CompteurSortesPlanetes = 0;

    public static int CompteurPlanetes = 0;
    public static int CompteurPlaneteTerre = 0;
    public static int CompteurPlaneteMars = 0;
    public static int CompteurPlaneteMercure = 0;
    public static int CompteurPlaneteJupiter = 0;
    public static int CompteurPlaneteVenus = 0;

    public static List<string> NbAleatMoins1Plus1;
    public static List<string> NbAleat01;
    public static List<string> NbAleat012;
    public static List<string> NbAleat0123;
    public static List<string> NbAleat01234;
    public static List<string> NbAleat01234567;

    private int IndiceNbAleatMoins1Plus1 = 0;
    private int IndiceNbAleat01 = 0;
    private int IndiceNbAleat012 = 0;
    private int IndiceNbAleat0123 = 0;
    private int IndiceNbAleat01234 = 0;
    private int IndiceNbAleat01234567 = 0;

    //Function to get random number
    // Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.
    private static readonly System.Random getrandom = new System.Random();
    private static readonly object syncLock = new object();
    public static int GetRandomNumber(int min, int max)
    {
        lock (syncLock)
        { // synchronize
            return getrandom.Next(min, max);
        }
    }

    void Update()
    {
        if (BouttonOKGO.JouerLaPartie) {
            if (TabPlanete.Length == 0) { 


                TabPlanete = new GameObject[CompteurSortesPlanetes]; 

                int i = 0;

                if (MenuParamPlanetes.UtiliserTerre) {
                    TabPlanete[i] = PlaneteTerreObjet;
                    i++;
                }
                if (MenuParamPlanetes.UtiliserMars) {
                    TabPlanete[i] = PlaneteMarsObjet;
                    i++;
                }
                if (MenuParamPlanetes.UtiliserMercure) {
                    TabPlanete[i] = PlaneteMercureObjet;
                    i++;
                }
                if (MenuParamPlanetes.UtiliserJupiter) {
                    TabPlanete[i] = PlaneteJupiterObjet;
                    i++;
                }
                if (MenuParamPlanetes.UtiliserVenus) {
                    TabPlanete[i] = PlaneteVenusObjet;
                    i++;
                }

            }

            tempo1 += Time.deltaTime;

            if ((tempo1 >= MenuParamPlanetes.DelaiAvantNouvellePlanete) && (CompteurPlanetes < MenuParamPlanetes.NBrePlanetesALancer)) {
                GameObject ClonePlanete;
                Vector2 OriginePlanete;

                OriginePlanete = new Vector2 (transform.position.x, transform.position.y);
                int IndiceAleatoire = GetRandomNumber (0, CompteurSortesPlanetes);
   
                ClonePlanete = (GameObject)Instantiate (TabPlanete [IndiceAleatoire], new Vector2 (OriginePlanete.x, OriginePlanete.y), transform.rotation);

                ClonePlanete.GetComponent<AjouteProprietes> ().InstantCreation = Time.timeSinceLevelLoad;

                switch (ClonePlanete.name) {
                case "Terre(Clone)":
                    CompteurPlaneteTerre++;
                    if (MenuParamPlanetes.DetruireTerre) {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "A detruire";
                    } else {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "Ne pas detruire";
                    }

                    break;
                case "Mars(Clone)":
                    CompteurPlaneteMars++;
                    if (MenuParamPlanetes.DetruireMars) {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "A detruire";
                    } else {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "Ne pas detruire";
                    }
                    break;

                case "Mercure(Clone)":
                    CompteurPlaneteMercure++;
                    if (MenuParamPlanetes.DetruireMercure) {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "A detruire";
                    } else {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "Ne pas detruire";
                    }
                    break;
                case "Jupiter(Clone)":
                    CompteurPlaneteJupiter++;
                    if (MenuParamPlanetes.DetruireJupiter) {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "A detruire";
                    } else {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "Ne pas detruire";
                    }
                    break;
                case "Venus(Clone)":
                    CompteurPlaneteVenus++;
                    if (MenuParamPlanetes.DetruireVenus) {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "A detruire";
                    } else {
                        ClonePlanete.transform.Find ("StatutDetruire").tag = "Ne pas detruire";
                    }
                    break;
                }

                CompteurPlanetes++;

                Vector2 CentreEcran = Vector2.zero;
                CentreEcran = Camera.main.transform.position;

                Vector3 DirectionPlanete;
                float bruitX = (MenuParamPlanetes.DispersionHorizPlanetes * UnityEngine.Random.Range (-1.0f, 1.0f));
                float bruitY = (MenuParamPlanetes.DispersionHorizPlanetes * UnityEngine.Random.Range (-0.8f, 0.8f));

                DirectionPlanete = new Vector2 (CentreEcran.x + bruitX, CentreEcran.y + bruitY) - OriginePlanete;

                ClonePlanete.GetComponent<Rigidbody> ().velocity = Vector3.Normalize (DirectionPlanete) * MenuParamPlanetes.ForceLancer;

                tempo1 = 0;
            }
        }

    }
}

Array index is out of range means, that you have an array with n size and you’re trying to get either the element with an index higher than n, or lower than 0

1 Like

Or if you try and acces an array with 0 elements in it.

Which line is the error on? Parsing 200 lines of code to look for one error is reaching the limit of my charity. But with a line number it should be pretty straight forward to diagnose.

1 Like

I made a mistake, not n+1 and above, n and above
and then , if n = 0, then accessing 0th or anything higher than that element is bad
EDIT:
I’m sure this sentence just doesn’t make sense

2 Likes

Got it i think

  • if (MenuParamPlanetes.UtiliserTerre) {
  • TabPlanete = PlaneteTerreObjet;
    • i++;*
    • }*
    • if (MenuParamPlanetes.UtiliserMars) {*
      - TabPlanete = PlaneteMarsObjet;
      - - i++;*
      - - }[/I][/I]*
      TabPlanete is empty, and i = 0 at the beginning, you add 1 to it, Error at line 6
      EDIT:
      I mean 71
1 Like

You’re instantiating your array to contain no elements.
You use

public static int CompteurSortesPlanetes = 0;
...
TabPlanete = new GameObject[CompteurSortesPlanetes];

Unless you’re setting the value of this variable somewhere else (higher than zero), you create an empty array, which means you can’t set objects at an arrayindex that does not exist. I’d suggest first of all to change your static variables to const, if they are constant, or remove the static. Statics should not be used when they’re not needed, and it feels like it doesn’t in this case. Then change the variable to contain all the objects that will be needed for the class. If it needs to hold 10 gameobjects, set it to then and so on.

2 Likes

Sorry I thought that I’ve put the line… It’s at lines 70/ 71…

Okey thanks I can’t replace the static variables by a constant one 'cause I need it in an other scipt and I delete “static” it does not work and same if it’s a constant one. But when I change the variable number I don not have errors anymore so I guess it comes from this.
Thanks very much for helping :slight_smile:

If you need it in another script you can fetch the gameobject in the scene, and use that reference to access everything you need, just look up stuff like GameObject.FindWithTag() or GameObject.Find() to find the object that contains the script. You could also add a variable in the script that needs the reference/script and drag it to your field property and use it that way.

Something like (not tested):

public class SomeScriptThatNeedsVariable : MonoBehaviour
{
// Drag your gameobject to this variable  in the inspector.
public CreationPlanetes planetCreator;

void Awake()
{
// print to the console the size of the planetCreator array
Debug.Log(planetCreator.CompteurSortesPlanetes);
}

}

I’m just guessing what CreationPlanetes means when naming that variable, but you can use anything you want.

1 Like