- Home /
Question by
RickTick · Jul 31, 2012 at 10:10 PM ·
javascriptarraysort
Sorting Array
Hi,
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.
Comment
Answer by whydoidoit · Jul 31, 2012 at 10:42 PM
I agree with @Fattie you should use a List<GameObject> and use the add and remove functions. In other respects List has the same [x] 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();
Your answer
![](https://koobas.hobune.stream/wayback/20220613075006im_/https://answers.unity.com/themes/thub/images/avi.jpg)