I've a list of buttons that I create using XML stored data. To achieve it, I've created a Prefab
. These buttons are created correctly, and now I want them to be sorted for the user.
public List<GameObject> myButtons;
As I said, now I want to sort them. I've found out that sorting the List
itself, buttons are sorted in the UI.
myButtons.Sort((x, y) => ...);
The problem is, that I don't have the necessary data to sort them within them. This leaves the .Sort()
method unavailable for use.
I've tried to sort them adding an script to each one, which contains the data that I need to use to sort them. However, it doesn't work correctly and I seem unable to find out why, so I'm wondering about other more direct methods to sort them.
Notice that I'm referring to simple buttons in a 2D game, and that they're all inside the same parent/gameobject
.
Technical Details
Let's start by the basics: I want to order the buttons taking into account if the user has reached a point in which the item it represents should be available
.
This is stored in an instance of a class that represents the items related to the buttons of the question.
public class myItemClass
{
# Here there are other properties
public bool available;
}
Therefore, we've a correspondence between two lists:
public List<myItemClass> myItems;
public List<GameObject> myButtons;
Where:
myItems[0] is related/represented by myButtons[0]
...
NOTICE that this relation exist at the initialization of the game, so i need to keep it at any moment (meaning, having to sort both lists).
What I tried
To be able to order my buttons depending on if the items are available or not, what I've done is:
- Creating an script
myItemScript
, which has a reference to my original items from the other list. - Sorted the items using
Sort
function over them.
public class myItemScript: MonoBehaviour {
public OtherClass.myItemClass dataObject;
}
And then sorting them like:
myButtons.Sort((x, y) => y.GetComponent<myItemScript>().dataObject.available.CompareTo(x.GetComponent<myItemScript>().dataObject.available));
As I said before, both list need to be following the same order, so just after it, I order the item list as well:
myItems.Sort((x, y) => y.available.CompareTo(x.available));
Checking/Debug
As result, I found that items were in fact sorting different. However:
- Items inside
myItems
List were sorted as expected. - Buttons in UI (and hence,
myButtons
List were not sorted as expected. Mixed items (available = true/false) were mixed and not ordered in two blocks, one first and then the other one.
This was checked using breakpoints within VS2017 and pausing the game in Unity interface.
Transform.SetSiblingIndex
, the question remains: how to do it optimally? \$\endgroup\$ – trollingchar Aug 9 '19 at 16:32