繁体   English   中英

为什么错误显示“ArgumentException:索引越界”。 当我在 Unity 中获得触摸增量位置时?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM