How do I organize a list of GameObjects (OrderByDescending?) based on the property of an attached component?
Hi, I'm new to the Forums, and pretty new to developing in C#.
I hope this comes out at least partially formatted so that it is readable. So sorry in advance if it doesn't.
Basically what I have going on in my game is:
Turn-based combat
Every combatant has "CombatantStats" attached, which includes the (public int) property "speed" assigned in the inspector)
I want the combatants for any individual encounter (triggered by collision, which works fine) to have turns in the order of their speed stat, from greatest to least.
Currently the way that I'm approaching this is I have an unordered list of GameObjects (player, to whom the script to initiate battle is attached; enemy, who is collided with and has "Enemy" tag; potentially other enemies or allies).
Finding a way to order this list by the property of a component that all of the GameObjects should have attached was challenging, but I found that System.Linq and OrderBy seemed like the right answer.
IEnumerable newOrder = order.OrderByDescending(combatant => combatant.GetComponent().speed);
I'm just not sure I have the syntax down quite right since I'm getting this error:
1. NullReferenceException: Object reference not set to an instance of an object BattleReady.m__0 (UnityEngine.GameObject combatant) (at Assets/Scripts/BattleReady.cs:102)
System.Linq.SortSequenceContext`2[UnityEngine.GameObject,System.Int32].Initialize (UnityEngine.GameObject[] elements) **
System.Linq.QuickSort`1[UnityEngine.GameObject].PerformSort () **
System.Linq.QuickSort`1+c__Iterator21[UnityEngine.GameObject].MoveNext () **
BattleReady.OrderTurns () (at Assets/Scripts/BattleReady.cs:103)
BattleReady.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/Scripts/BattleReady.cs:65)
BattleReady.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/Scripts/BattleReady.cs:65)