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