- Home /
argumentexception: index out of bounds
Hey,
This is probably a really easy question, but i am new in unity and i cant fixed it. I want to only one touch. if people touch it twice. it becomes 2 touches.
UnityException: Index out of bounds.
can somebody help me?
void Update()
{
Touch touch =Input.GetTouch(0);
if (dead)
{
DCD -= Time.deltaTime;
if (DCD <= 0)
{
if (Input.GetTouch(0).tapCount > 0)
{
Application.LoadLevel(Application.loadedLevel);
VFalse.SetActive(true);
}
}
}
else
{
if (Input.touchCount > 0 && touch.phase == TouchPhase.Began)
didFlap = true;
}
}
Answer by doublemax · Oct 14, 2016 at 09:46 AM
With "Input.GetTouch(0)" you're assuming that there is already at list one touch in the list. But this is not guaranteed. Before accessing it, you need to check if "Input.touchCount" is > 0.
yes, exactly, Input.touchCount basically gives you Input.touches array count, so that you know IF you can call Input.GetTouch(), and what's the upper bound you can call it with.
https://docs.unity3d.com/ScriptReference/Input-touchCount.html
Within one frame, imagine person tapping with two fingers: Input.touchCount will be 2 Input.GetTouch(0) will return the (chronologically) info about the first finger/point where user touches the screen, and Input.GetTouch(1) will return the second one.
if, in the next frame, user keeps the two fingers on the screen, and adds another one, Input.touchCount will be 3, and Input.GetTouch(2) will contain info about this new point, while GetTouch(0) and (1) will hold the info about the (progress of) previous two touches.
my english is not perfect so where i must to change ?
in short, everywhere. rewrite the whole code.
check if there was any touch done
Touch touch; if(Input.touchCount > 0) touch =Input.GetTouch(0);
then everywhere where you try to access the info about the touch, you need this as the first condition:
if(touch != null && [anything you need to check for within the touch info])