Reputation: 1
I have written the following program to detect touch input with mouse as well as swipe input on a mobile device.
The mobile part works great with the Unity's Device Simulator. However, the mouse part throws the following error:
IndexOutOfRangeException: Index was outside the bounds of the array.
What am I missing here?
using UnityEngine;
public class SwipeDetection : MonoBehaviour
{
public Player _Player;
private Vector2 _startPos;
private bool _fingerDown;
public int _PixelDistToDetect = 50;
private void Start()
{
_startPos = transform.position;
}
private void Update()
{
#region MOBILE TOUCH
if (!_fingerDown && Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
{
_fingerDown = true;
_startPos = Input.touches[0].position;
}
if (_fingerDown)
{
if (Input.touches[0].position.y >= _startPos.y + _PixelDistToDetect) // up
{
_fingerDown = false; Debug.Log( string.Format("<color=red><b><size=15> UP </size></b></color>") );
}
else if (Input.touches[0].position.x <= _startPos.x - _PixelDistToDetect) // left
{
_fingerDown = false; Debug.Log( string.Format("<color=red><b><size=15> LEFT </size></b></color>") );
}
else if (Input.touches[0].position.x >= _startPos.x + _PixelDistToDetect) // right
{
_fingerDown = false; Debug.Log( string.Format("<color=red><b><size=15> RIGHT </size></b></color>") );
}
else if (Input.touches[0].position.y <= _startPos.y - _PixelDistToDetect) // down
{
_fingerDown = false; Debug.Log( string.Format("<color=red><b><size=15> DOWN </size></b></color>") );
}
}
if (_fingerDown && Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Ended)
{
_fingerDown = false;
}
#endregion MOBILE TOUCH
#region MOUSE DRAG
if (!_fingerDown && Input.GetMouseButtonDown(0))
{
_fingerDown = true;
_startPos = Input.mousePosition;
}
if (_fingerDown)
{
if (Input.mousePosition.y >= _startPos.y + _PixelDistToDetect) // up
{
_fingerDown = false; Debug.Log( string.Format("<color=red><b><size=15> UP </size></b></color>") );
}
else if (Input.mousePosition.x <= _startPos.x - _PixelDistToDetect) // left
{
_fingerDown = false; Debug.Log( string.Format("<color=red><b><size=15> LEFT </size></b></color>") );
}
else if (Input.mousePosition.x >= _startPos.x + _PixelDistToDetect) // right
{
_fingerDown = false; Debug.Log( string.Format("<color=red><b><size=15> RIGHT </size></b></color>") );
}
else if (Input.mousePosition.y <= _startPos.y - _PixelDistToDetect) // down
{
_fingerDown = false; Debug.Log( string.Format("<color=red><b><size=15> DOWN </size></b></color>") );
}
}
if (_fingerDown && Input.GetMouseButtonUp(0))
{
_fingerDown = false;
}
#endregion MOUSE DRAG
}
}
Upvotes: 0
Views: 181
Reputation: 176
because you code (in Mobile Drag section) set _fingerDown to true So, next frame update call
if (_fingerDown) ...
on Mobile touch section and Input.touch always null (while on pc) and you invoke Input.touches[0] that way IndexOutOfBound are thrown
Upvotes: 1