Sorting Array


I got

public var inventory : GameObject[] = new GameObject[20];

and I am always adding and deleting objects in this array. So after some time I have some gaps in my inspector, empty elements.

Is there a function to sort the elements in javascript? A simple inventory.Sort(); doesn’t seem to work the way I expected.

I agree with @Fattie you should use a List and use the add and remove functions. In other respects List has the same semantics as an array.

You can sort any array or list using Linq

   import System.Linq;

   var sortedArray = inventory.OrderBy(function(go) { return go.GetComponent(YourScript).yourVariable; }).ToArray();
   var sortedList = inventory.OrderBy(function(go) { return go.rigidbody.position.x; }).ToList();