Aniket Malik
Aniket Malik

Reputation: 335

How to encounter with error-"InvalidOperationException: Operation is not valid due to the current state of the object" upon use of System.Linq

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

public class qtpye : MonoBehaviour {
    public LineRenderer lr;
    public EdgeCollider2D ec;
    public List<Vector3> points;
    private bool jok=true;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (jok ==false&Vector3.Distance(points.Last(),transform.position)>0.7f)
            {
            points.Add (transform.position);
            lr.positionCount = points.Count;
            lr.SetPosition (points.Count - 1, new Vector3 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y, transform.position.z));
        }



    }
    void OnMouseDown()
    {jok = false;
        Debug.Log ("f");
    }
    void OnMouseUp()
    {jok = true;

    }

}

I am trying to use line renderer however error comes up for
if (jok ==false&Vector3.Distance(points.Last(),transform.position)>0.7f) which is

InvalidOperationException: Operation is not valid due to the current state of the object System.Linq.Enumerable.Last[Vector3] (IEnumerable`1 source) qtpye.Update () (at Assets/qtpye.cs:18)

Upvotes: 1

Views: 2093

Answers (1)

Izuka
Izuka

Reputation: 2612

List.Last() will return an InvalidOperationException if your list is empty. You gotta make sure your list contains at least one point before calling this function. You can for instance add the first point whenever your list is empty, and make the verification you are doing on the distance for the others.

Also, your if statement is wrong. You didn't use the AND operator which is &&, because you forgot one &.

In the end, you can go for something like this:

if (jok ==false && (points.Count == 0 || Vector3.Distance(points.Last(),transform.position)>0.7f  Vector3.Distance(points.Last(),transform.position)>0.7f))

Upvotes: 2

Related Questions