Click here to Skip to main content
15,886,545 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Index was out of range. Must be non-negative and less than the size of the collection



This is the Code in Visual Studio for Unity

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

public class DrawLine : MonoBehaviour
{
    public GameObject linePrefab;
    public GameObject currentLine;

    //public LineRenderer OriginalLine;

    public LineRenderer lineRenderer;
    public List<Vector2> fingrePositions;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if(Physics.Raycast(ray, out hit))
            {
                Debug.Log("hit.transform.name");

                if(hit.transform.name == "EmpetySpace")
                {
                    CreateLine();
                }
            }
        }

        if (Input.GetMouseButton(0))
        {
            Vector2 tempFingerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            if (Vector2.Distance(tempFingerPos, fingrePositions[fingrePositions.Count - 1]) > 0.1f)
            {
                UpdateLine(tempFingerPos);
            }
        }

        if (Input.GetMouseButtonUp(0))
        {
            enabled = false;
        }
    }

    void CreateLine()
    {
        currentLine = Instantiate(linePrefab, Vector3.zero, Quaternion.identity);
        lineRenderer = currentLine.GetComponent<LineRenderer>();
        fingrePositions.Clear();
        fingrePositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
        fingrePositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
        lineRenderer.SetPosition(0, fingrePositions[0]);
        lineRenderer.SetPosition(1, fingrePositions[1]);
    }

    void UpdateLine(Vector3 newFingerPos)
    {
        fingrePositions.Add(newFingerPos);
        lineRenderer.positionCount++;
        lineRenderer.SetPosition(lineRenderer.positionCount - 1, newFingerPos);
    }
}


What I have tried:

if i press on a gameObject then the code works perfectly fine. But when i click anywhere on the screen other than the gameObject then this error appears
Posted
Updated 6-Apr-20 9:29am

Indexes in C# run from 0 to N - 1 inclusive, where N is the number of items in the collection.
So if your have 5 elements in an array arr, say, then valid indexes would be
C#
arr[0]
arr[1]
arr[2]
arr[3]
arr[4]
Any other value as an index (i.e. negative, or greater than or equal to N) will cause an index out of range exception because there is no value at that location.

We can't tell you what the problem is in your code precisely: it needs your code running with your data to work that out, and we don't have access to that at all.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
 
Share this answer
 
Quote:
Index was out of range. Must be non-negative and less than the size of the collection

Iy means exactly what it says. The exact error message tells you line where error happen.
For some reason, probably depending on data, an array/list/vector is smaller that expected and you try to read/write a value in a position that does not exist.
The tool of choice is the debugger.

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

Debugging C# Code in Visual Studio - YouTube[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900