How to display items in a list, in a certain order for Unity UI

Viewed 29

At first, my code:

public void CreateDisplay()
{
    for (int i = 0; i < inventory.Container.Count; i++)
    {
        var obj = Instantiate(inventory.Container[i].item.DefaultPrefab, Vector3.zero, Quaternion.identity, transform);
        obj.GetComponent<RectTransform>().localPosition = GetPosition(i);
        obj.GetComponentInChildren<TextMeshProUGUI>().text = inventory.Container[i].level.ToString();
    }
}

public Vector3 GetPosition(int i)
{
    return new Vector3(X_START + (X_SPACE_BETWEEN_ITEM * (i % NUMBER_OF_COLUMN)), Y_START + (-Y_SPACE_BETWEEN_ITEM * (i / NUMBER_OF_COLUMN)), 0f);
}

I am trying to display the items of a List in an order like this.

1   4   7
2   5   8
3   6   9

At the moment, they are displayed from left to right and start a new line after the NUMBER_OF_COLUMN was hit.

Does anyone have an idea for a formula that could work with that? I tried some things but it never worked the way it supposed to.

1 Answers

If you want to swap columns with rows, you need to swap parts of code that calculates x and y of each item.

Just put (i % NUMBER_OF_COLUMN) in place of (i / NUMBER_OF_COLUMN) and vice versa.

Related