I need help with a script I am working on

This is a swipe controller code and when i try to swipe the player i have an error:
IndexOutOfRangeException: Index was outside the bounds of the array.
SwipeManager.SendSwipe () (at Assets/Scripts/SwipeManager.cs:65)
SwipeManager.Update () (at Assets/Scripts/SwipeManager.cs:57)

script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwipeManager : MonoBehaviour
{
    public static SwipeManager instance;

    public enum Direction { Left, Right};
    bool[] swipe = new bool[2];

    Vector2 startTouch;
    bool touchMoved;
    Vector2 swipeDelta;

    const float SWIPE_THERESHOLD = 50;

   Vector2 TouchPosition() {return (Vector2)Input.mousePosition;}
   bool TouchBegan() {return Input.GetMouseButtonDown(0); }

   bool TouchEnded() {return Input.GetMouseButtonUp(0); }

   bool GetTouch() {return Input.GetMouseButton(0);}

   void Awake() { instance = this; }

  
    void Update()
    {
        //START FINISH
        if(TouchBegan())
        {
            startTouch = TouchPosition();
            touchMoved = true;
        }
        else if(TouchEnded() && touchMoved == true)
        {
            SendSwipe();
            touchMoved = false;
        }
        //CALC DISTANCE
        swipeDelta = Vector2.zero;
        if(touchMoved && GetTouch())
        {
            swipeDelta = TouchPosition() - startTouch;
        }

        //CHECK SWIPE
        if(swipeDelta.magnitude > SWIPE_THERESHOLD)
        {
            if(Mathf.Abs(swipeDelta.x) > Mathf.Abs(swipeDelta.y))
            {
                //LEFT/RIGHT
                swipe[(int)Direction.Left] = swipeDelta.x < 0;
                swipe[(int)Direction.Right] = swipeDelta.x > 0;
            }
            SendSwipe();
        }

    }
    void SendSwipe()
    {
        if (swipe[0] || swipe[1] || swipe[2] || swipe[3])
        {
            Debug.Log(swipe[0] + "|" + swipe[1] + "|" + swipe[2] + "|"  + swipe[3]);
        }
        else
        {
            Debug.Log("Click");
        }
        Reset();
    }

    private void Reset()
    {
        startTouch = swipeDelta = Vector2.zero;
        touchMoved = false;
        for(int i=0; i < 4; i++) { swipe[i] = false;}
    }

}

8207295–1071168–SwipeManager.cs (1.96 KB)

On line 65. you try to Debug.Log something which is null at the index of your array you try to reach

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

Steps to success:

  • find which collection it is (critical first step!)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection
  • remember you might have more than one instance of this script in your scene/prefab

Thank you very much for your help!

1 Like