c # – Sort the buttons in the 2D unit

I have a list of buttons that I create using XML stored data. To achieve this, I created a Prefab. These buttons are created correctly and I now want them to be sorted for the user.

public List myButtons;

As I said, now I want to sort them. I discovered that sorting List itself, the buttons are sorted in the user interface.

myButtons.Sort((x, y) => ...);

The problem is that I do not have the data to sort them. That leaves the .Sort() method not available for use.

I've tried sorting them out by adding a script to each of them, which contains the data I need to use to sort them. However, it does not work properly and I seem unable to know why, so I ask myself about other more direct methods to sort them out.

Notice that I'm referring to simple buttons in a 2D game and that they are all inside the same parent/gameobject.

enter the description of the image here

Technical details

Let's start with the basics: I want to control the buttons taking into account whether the user has reached a point where the article he represents should be available.

This is stored in an instance of a class that represents the items related to the question buttons.

public class myItemClass
        # Here there are other properties
        public bool available;

Therefore, we have a correspondence between two lists:

public List myItems;
public List myButtons;


myItems (0) is linked / represented by myButtons (0)

NOTICE that this relationship exists at the initialization of the game, so I have to keep it at all times (that is, I have to sort the two lists).

What I've tried

To be able to order my buttons according to the availability of articles, here is what I did:

  1. Create a script myItemScript, which has a reference to my original articles from the other list.
  2. Sorted items using Sort operate on them.
public class myItemScript: MonoBehaviour {
    public OtherClass.myItemClass dataObject;

And then sorting them as:

myButtons.Sort((x, y) => y.GetComponent().dataObject.available.CompareTo(x.GetComponent().dataObject.available));

As I have already said, the two lists must follow the same order, so right after, I also order the list of articles:

myItems.Sort((x, y) => y.available.CompareTo(x.available));

Verification / debugging

As a result, I found that the items actually sorted differently. However:

  • Articles inside myItems List were sorted as expected.
  • Buttons in the user interface (and therefore myButtons The list was not sorted as expected. Mixed items (available = true / false) were mixed and not ordered in two blocks, one at first, then the other.

This was verified using the VS2017 stopping points and putting the game in pause in the Unity interface.