index out of bounds

Hey,

This is probably a really noob question, but I cannot find the answer. The following code gives:

UnityException: Index out of bounds.

can somebody point me to why I'm failing here:

if ((Input.GetTouch(0).phase == TouchPhase.Began)  && !isPaused )
{
   //Do something
}

Thanks a Lot!

6 Answers

6

Wild guess: Use iPhoneTouch.GetTouch(0), not Input. But the error message would be bizarre if that's the answer.

Hey, Thanks! Didn't work though. The problems seems to occur if the code is not in a for loop.. do you know if this has to be the case?

I solved the problem i was having by assigning the value i wanted (the touch position) to a variable and using that instead.

still puzzled as to why I was getting the error, and not getting it in the following.

if (Input.touchCount > 0)
{
    // Get position of the first finger
    var touchPosition : Vector2 = Input.GetTouch(0).position;
}

Ah, ok, it seems internally touches are stored in some kind of dynamic array. When calling Input.GetTouch(0) you access the first element of that array, but the array apparently is empty when there are no touches. Hence the out-of-bounds. I never worked with iPhone, so I didn't know that. Glad it worked out for you.

Cool! that makes sense. If you make an answer of it i can give you the points. Thanks!

I think its because since the Touches are stored in an array, you have to iterate through it (like they have shown in the documentations) according to the touchCounts registered. If not, like Wolfram mentioned, you will be accessing the first element of an empty array.

I can fix this problem by add condition: if(Input.touchCount > 0)
I put my code in Update() function so at the beginning, when i have no touch, this code still run, i think the problem is come from there

a same problem

i fix with GetLenght:

    // Return X or Y Coord of touch - Use Ex: ToqueCoord ('x', i); i as index of touch; 

int ToqueCoord(char c, int i) {
	int x = 0, y = 0; 
	int t = Input.touches.GetLength (0);

	Debug.Log (t);

	if (t >= (i)) {
		x = (int)Input.touches [i - 1].position.x;
		y = (int)Input.touches [i - 1].position.y;
		Debug.Log ("OK");
	}

	if (c == 'x') {
		return (x);
	}
	if (c == 'y') {
		return (y);
	}
			
	return (0);
}

Problem fixed here : index out of bounds unity - YouTube