【问题标题】:How to encounter with error-"InvalidOperationException: Operation is not valid due to the current state of the object" upon use of System.Linq使用 System.Linq 时如何遇到错误-“InvalidOperationException: Operation is not valid due to the current state of the object”
【发布时间】:2017-06-01 10:46:07
【问题描述】:
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;

    }

}

我正在尝试使用线条渲染器,但出现错误
if (jok ==false&amp;Vector3.Distance(points.Last(),transform.position)&gt;0.7f) 这是

InvalidOperationException:操作无效,因为当前 对象 System.Linq.Enumerable.Last[Vector3] 的状态 (IEnumerable`1 来源) qtpye.Update () (at Assets/qtpye.cs:18)

【问题讨论】:

  • 您的if 语句语法错误,因为它指出if (X == false &amp; Y &gt; Z) 使用双&amp;&amp; 来修复错误

标签: c# list unity3d


【解决方案1】:

List.Last() 如果您的列表为空,将返回 InvalidOperationException。在调用此函数之前,您必须确保您的列表至少包含一个点。例如,您可以在列表为空时添加第一个点,并为其他点进行距离验证。

另外,你的 if 语句是错误的。您没有使用 AND 运算符,即 &&,因为您忘记了一个 &。

最后,你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-15
    • 2022-12-26
    • 1970-01-01
    • 2022-12-27
    • 1970-01-01
    • 2022-12-02
    • 2022-12-02
    • 2022-06-17
    相关资源
    最近更新 更多