- Home /
Ordering an array of GO based on interfaced variables using linq.
So for example I have characters with this script:
public class Player : MonoBehaviour, IEntity {
private int _speed = 5; //(Different characters have different speeds)
public int Speed { get{return _speed;} set{_speed = value;} }
}
with this interface:
public interface IEntity{
int Speed { get; set; }
}
And I want to order an array of all players. I researched and came up with this function but it doesn't work. Can anyone point me in the right direction? thanks.
.
.
.
var sortedArray = _allEntities.OrderBy(go => CompareCondition(go)).ToArray();
}
int CompareCondition(GameObject go)
{
var property = (IEntity)go.GetComponent(typeof(IEntity));
return property.Speed;
}
Comment
Best Answer
Answer by fafase · May 04, 2014 at 09:36 AM
list.Sort( (objA,objB)=>objA.Speed.CompareTo(objB.Speed) );
yes because Linq is nice and easy but not recommended in game when possible. Linq does a lot a hidden work that piles up garbage. In Linq:
_allEntities.OrderBy(obj=>obj.Speed).ToArray();