Question by
LeftEyeScar · Sep 06, 2016 at 10:53 AM ·
c#unity 5gameobjectarray
How do you order an array by numbers held in Game Object String
I am currently creating a 2D game where you have to diffuse a bomb, and I need the bomb parts to be in certain order layers/sorting layers for it to work. I assign them on runtime as there is a procedural element of the game. However, when I make an array to hold gameobjects with tag "BombPart", it puts them in randomly, and I need them ordered for my other script to work.
Any help? The below code doesn't work, but I though System.Linq might work.
GameObject[] bombPartGameObjects;
public void Assign(){
bombPartGameObjects = GameObject.FindGameObjectsWithTag("bombPart").OrderBy(bombPartGameObjects => bombPartGameObjects.GetComponent().sortingOrder).ToArray();
}
Comment
Does it even compile?
What's the result?
Just a guess, but GetComponent() does not do anything. You probably meant GetComponent().sorting Order ?
Use a List.Sort with a comparefunction.
GameObject[] bombPartGameObjects;
public void Assign()
{
GameObject[] parts = GameObject.FindGameObjectsWithTag("bombPart");
List<GameObject> list = new List<GameObject>(parts);
list.Sort(CompareFunction);
bombPartGameObjects = list.ToArray();
}
private int CompareFunction(GameObject a, GameObject b)
{
$$anonymous$$yScript aScript = a.GetComponent<$$anonymous$$yScript>();
$$anonymous$$yScript bScript = b.GetComponent<$$anonymous$$yScript>();
if (!b)
{
if (!a)
{
return -1;
}
return 0;
}
if (!a)
{
return 1;
}
return aScript.sortingOrder.CompareTo(bScript.sortingOrder);
}