[英]Why error is showing "ArgumentException: Index out of bounds." when I get touch delta position in Unity?
I am trying to rotate a gameObject using raycast.我正在尝试使用 raycast 旋转游戏对象。 When I run unity editor getting the error当我运行统一编辑器时出现错误
ArgumentException: Index out of bounds. ArgumentException:索引越界。 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) 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;
第 27 行是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);
}
Input.GetTouch
uses an index to find the status of a specific touch.Input.GetTouch
使用索引来查找特定触摸的状态。 If there are no touches then it throws the Index out of bounds
error.如果没有触摸,则会抛出Index out of bounds
错误。
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.由于您在Update
方法中调用代码,因此每帧都会对其进行检查,即使您没有对游戏进行任何输入。
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:您需要做的是检查自上次使用Input.touchCount
调用Update
以来是否有触摸,然后获取触摸:
if (Input.touchCount > 0)
{
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
}
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)
行Input.GetTouch(0)
if 语句之外时,如下所示,我都会收到错误消息:
Input.GetTouch(0);
if (Input.touchCount > 0)
{
}
However, if I keep it inside the if-statement like below the error is gone:但是,如果我将其保留在如下所示的 if 语句中,则错误消失了:
if (Input.touchCount > 0)
{
Input.GetTouch(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.