The operation is invalid due to the current state of the object - Linq on List

This error occurs when starting a Linq query on a list.

I am using Unity3D 3.0 with C # (Unity3D uses Mono 2.6). Unity3D, as far as I know, is single-threaded. It works by attaching "scripts" (C # .cs files) that inherit the base class to "GameObject". In addition, Unity controls instance creation and script serialization, so you cannot use constructors.

I have a RoadNetwork script that contains a link to RoadNodes and RoadCurves, both of which install RoadNetwork through one singleton and register / unregister. I put the “mini-factories" in RoadNode and RoadCurve, which work hard to connect to the game object.

RoadNode first checks with RoadNetwork to make sure that the node is no longer in the same position by doing the following:

public static RoadNode2 New(float x, float y, float z)
{
    //First try to find an existing one
    var rn = RoadNetwork.Instance.GetNodeAtPosition(new Vector3(x, y, z))
             ?? UnityReferenceHelper.GetNewGameObjectFor<RoadNode2>(
                 "RoadNode_" + (RoadNetwork.Instance.Nodes.Count + 1).ToString("D3"),
                 RoadNetwork.Instance.transform.FindChild("Nodes"));

    rn.Position = new Vector3(x, y, z);

    rn.gameObject.active = true;

    return rn;
}

If the appropriate method in RoadNetwork:

public RoadNode2 GetNodeAtPosition(Vector3 position)
{
    var tempList = new List<RoadNode2>();

    return tempList.Single(x => x.Position == position);
}

tempList was an attempt to narrow down the problem, but I am getting exactly the same error. It should be "Nodes.Single (...", but I doubt it matters. I get the same error if I call the Linq query directly in the New () method.

So yes, this exception throws and points to this line tempList.Single (). What is the reason?

+5
source share
3 answers

someEnumerable.Single(...)throws an exception if in someEnumerableone element does not exist. Given that you simply declared tempListan empty list, it will always throw an exception.

null, , SingleOrDefault. ( - , .) , , First ( , ) FirstOrDefault ( null ).

, , - , , Any.

+13

, , .Single() , . someEnumerable ( ), .

0

, , singleton Unity. , , , , , , , .

singleton MonoBehaviour, GameObject, :

http://answers.unity3d.com/questions/156746/singleton-and-monobehaviour-in-editor.html

0
source

All Articles