- Home /
problem with array index out of range
hi guys i trying to make my player object to collide with the cube object which by right will print out laps 1 on the race track .but there an error which said "array index is out of range"and i can't figure out why can anyone help me?
here is the script for cube object:
function OnTriggerEnter (other : Collider) {
//Is it the Player who enters the collider?
if (!other.CompareTag("Player"))
return; //If it's not the player dont continue
//Is this transform equal to the transform of checkpointArrays[currentCheckpoint]?
if (transform==playerTransform.GetComponent(player).checkPointArray[player.currentCheckpoint].transform) {
//Check so we dont exceed our checkpoint quantity
if (player.currentCheckpoint+1<playerTransform.GetComponent(player).checkPointArray.length) {
//Add to currentLap if currentCheckpoint is 0
if(player.currentCheckpoint==0)
player.currentLap++;
player.currentCheckpoint++;
} else {
//If we dont have any Checkpoints left, go back to 0
player.currentCheckpoint=0;
}
visualAid(); //Run a coroutine to update the visual aid of our Checkpoints
//Update the 3dtext
Camera.main.GetComponentInChildren(TextMesh).text = "Checkpoint: "+(player.currentCheckpoint)+" Lap: "+(player.currentLap);
}
}
None else can't figure it out without seeing your project. Just make sure that player.currentCheckpoint is in the array range of checkPointArray.
please don't invent a new tag (array-out-range-except) when there's a perfect equivalent already in existence (array-out-of-range-except). Thank you.
Answer by aldonaletto · Aug 05, 2011 at 03:23 PM
I could not find any error in your script, since it already checks the array length before incrementing currentCheckpoint. I only found somewhat weird the use of GetComponent to access checkPointArray - since currentCheckpoint is a static var, I suppose checkPointArray is static too. Is it true? I would make checkPointArray static, then access it using player.checkPointArray, like below:
if (transform == player.checkPointArray[player.currentCheckpoint].transform) { //Check so we dont exceed our checkpoint quantity if (player.currentCheckpoint+1 I already had some trouble with complicated constructions using GetComponent, so I try to simplify them whenever possible.
Another possible cause for this error is some other script altering currentCheckpoint.
Your answer
![](https://koobas.hobune.stream/wayback/20220612170348im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
IndexOutOfRange error on iPhone, but not on PC/Player 0 Answers
Array index is out of range 1 Answer
IndexOutOfRangeException: Array index is out of range. 2 Answers
Find if no objects with tag exist 3 Answers
Instantiating random prefabs 1 Answer