I have this method. It´s for ordering actors and only displaying the ones which are in direct line of sight with the player.

public Actor OrderActorListByDistance(List<Actor> list, Vector2 pos)
    return list.FindAll(d => Physics2D.Linecast(d.transform.position, pos, LayerMask.GetMask("Default")).collider == null).OrderBy(i => Vector2.Distance(pos, i.transform.position)).First();

But that Method throws that error InvalidOperationException: Operation is not valid due to the current state of the object

I already made a lot of google research but I couldn´t find any solution. I would appreciate any suggestion or help. Thanks in advance

  • 1
    \$\begingroup\$ Have you already figured out which method in that line throws the exception? \$\endgroup\$
    – Philipp
    Commented Jun 9, 2019 at 20:45
  • \$\begingroup\$ @Philipp yeah I did... I´m sorry it´s the return line \$\endgroup\$ Commented Jun 10, 2019 at 7:31
  • \$\begingroup\$ Although having these super long lines of code look nice and "hey, look what I can do!", they tend to make debugging harder. In the future, you might want to split this kind of code into each of it's independent steps to help figure out where is the bug coming from exactly. \$\endgroup\$
    – Vaillancourt
    Commented Jun 10, 2019 at 14:17
  • \$\begingroup\$ That´s a fair point. I´m not doing that to show off ;). I tend to do that because I like it short and this line is easy to understand. You just follow the point notation. But for debugging it would probably make more sense to break into parts as you said. @AlexandreVaillancourt \$\endgroup\$ Commented Jun 11, 2019 at 8:11

1 Answer 1


My guess is the use of .First() at the end there is the problem. That method will return the first element in the collection it is called on, but will throw an InvalidOperationException if the collection is empty, which is probably going to be the case at least some times.

Basically, change First to FirstOrDefault and make sure that the calling code can handle a null return value.

  • \$\begingroup\$ Thank you, it was just that simple. :) \$\endgroup\$ Commented Jun 10, 2019 at 8:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .