0
\$\begingroup\$

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

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Have you already figured out which method in that line throws the exception? \$\endgroup\$ – Philipp Jun 9 '19 at 20:45
  • \$\begingroup\$ @Philipp yeah I did... I´m sorry it´s the return line \$\endgroup\$ – Pascal Lohscheidt Jun 10 '19 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 Jun 10 '19 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\$ – Pascal Lohscheidt Jun 11 '19 at 8:11
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you, it was just that simple. :) \$\endgroup\$ – Pascal Lohscheidt Jun 10 '19 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.