0

I am trying to rotate a gameObject using raycast. When I run unity editor getting the error

ArgumentException: Index out of bounds. UnityEngine.Input.GetTouch (Int32 index) (at /Users/builduser/buildslave/unity/build/artifacts/generated/bindings_old/common/Core/InputBindings.gen.cs:619) AdjustTransform.Update () (at Assets/AdjustTransform.cs:27)

Line 27 is Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition; in the below code. What I am doing wrong here?

 void Update()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

    if (Physics.Raycast(ray,out hit,100))
    {

        Debug.Log(" GO Name "+hit.collider.gameObject.name);
    }

if(  Input.touchCount == 2 && !EventSystem.current.IsPointerOverGameObject() )
    {


            hit.collider.gameObject.transform.Rotate(Vector3.up, -touchDeltaPosition.x * rotspeed * Time.deltaTime, Space.World);
            hit.collider.gameObject.transform.Rotate(Vector3.right, touchDeltaPosition.y * rotspeed * Time.deltaTime, Space.World);


    }
You Nguyen
  • 9,961
  • 4
  • 26
  • 52
zyonneo
  • 1,319
  • 5
  • 25
  • 63

2 Answers2

6

Input.GetTouch uses an index to find the status of a specific touch. If there are no touches then it throws the Index out of bounds error.

Since you are calling the code in your Update method, it is being checked every frame, even if you haven't had any input to your game.

What you need to do is check that there are touches since the last time Update was called using Input.touchCount, then get the touch:

if (Input.touchCount > 0)
{
    Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
}
Steve
  • 9,335
  • 10
  • 49
  • 81
0

One of the problems that I've realized with this is that every time that I put the line Input.GetTouch(0) outside of the if-statement like below I get an error:

Input.GetTouch(0);

if (Input.touchCount > 0)
{

}

However, if I keep it inside the if-statement like below the error is gone:

if (Input.touchCount > 0)
{
    Input.GetTouch(0);
}
Das_Geek
  • 2,775
  • 7
  • 20
  • 26