【问题标题】:Why error is showing "ArgumentException: Index out of bounds." when I get touch delta position in Unity?为什么错误显示“ArgumentException:索引超出范围”。当我在 Unity 中获得触摸增量位置时?
【发布时间】:2018-09-28 05:10:08
【问题描述】:

我正在尝试使用 raycast 旋转游戏对象。当我运行统一编辑器时出现错误

ArgumentException:索引超出范围。 UnityEngine.Input.GetTouch (Int32 索引)(在 /Users/builduser/buildslave/unity/build/artifacts/generated/bindings_old/common/Core/InputBindings.gen.cs:619) AdjustTransform.Update()(在 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.touchCount的值是多少?
  • @mjwills...我把它作为 2.if 我用两根手指触摸。
  • 如果你看到这个错误,那肯定是0,按照下面的答案。

标签: c# unity3d


【解决方案1】:

Input.GetTouch 使用索引来查找特定触摸的状态。如果没有触摸,则会引发 Index out of bounds 错误。

由于您在 Update 方法中调用代码,因此每帧都会检查它,即使您的游戏没有任何输入。

您需要做的是检查自从上次使用 Input.touchCount 调用 Update 后是否有触摸,然后进行触摸:

if (Input.touchCount > 0)
{
    Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
}

【讨论】:

    【解决方案2】:

    我意识到的一个问题是,每次我将 Input.GetTouch(0) 行放在 if 语句之外,如下所示,我都会收到一个错误:

    Input.GetTouch(0);
    
    if (Input.touchCount > 0)
    {
    
    }
    

    但是,如果我把它放在里面,下面的 if 语句就会消失:

    if (Input.touchCount > 0)
    {
        Input.GetTouch(0);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多