How To Store and Act on Get Component Result in Linq Query?

How do I simplify the following linq query so that I am only doing one GetComponent call instead of two?

units = GameObject.FindGameObjectsWithTag(“enemy”).OrderByDescending(x => x.GetComponent().Initiative).Select(x => x.GetComponent()).ToArray();

I’d like to be able to select each Unit and then sort the list by its initiative.

1 Answer

1

Flip the select and ordering around:

units = GameObject.FindGameObjectsWithTag(“enemy”).Select(x => x.GetComponent()).OrderByDescending(x => x.Initiative).ToArray();

Great, thanks!