WokerHead
WokerHead

Reputation: 967

Unity: Problem with Index was outside the bounds of the array

I'm drawing using LineRenderer but I enable and disable the gameobject where the script is at different times.

The first enable it works perfect, after I disable and enable, I get this error

IndexOutOfRangeException: Index was outside the bounds of the array.

error shows to this line of code

Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.touches[0].position);

Here is all the code

public GameObject linePrefab;
private Line activeLine;

private void Update()
{
    if (Input.touchCount > 0)
    {
        if (Input.GetTouch(0).phase == TouchPhase.Began)
        {
            GameObject lineGO = Instantiate(linePrefab);
            activeLine = lineGO.GetComponent<Line>();
        }

        if (Input.GetTouch(0).phase == TouchPhase.Ended)
        {
            activeLine = null;
        }
    }

    if (activeLine != null)
    {
        Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.touches[0].position);
        activeLine.UpdateLine(touchPos);
    }
}

Upvotes: 0

Views: 5220

Answers (1)

Louis Ingenthron
Louis Ingenthron

Reputation: 1368

You're assuming the user is touching the screen in your code.

You need to check if there are any active touches before processing the touch position. Specifically, you can add to your if check whether or not Input.touchCount > 0

Upvotes: 1

Related Questions