Automated level button system
I am trying to create a level UI so I can easily change the number of level buttons and so that they will automatically scale to any phone size. I have a problem where I can space the buttons correctly but can't center them properly. I think it is something to do with the anchor points on the level canvas that I am instantiating them on.
Does anyone have any ideas of what I can try?
This is what I have so far:
// Objects
public GameObject buttonTemplate;
public GameObject parent;
// Number of rows and columns
private int maxRows = 4;
private int maxCols = 4;
private int buttonNum = 0;
// Button position
private Vector3 pos = default;
// X and Y spacing between buttons
public Vector2 spacing;
public Vector2 offset;
public RectTransform rectTransform;
// Levels created
public int levelsCreated = 20;
public int activeButtons;
void SetupButtons()
{
DataManagement.dataManagement.LoadData();
activeButtons = DataManagement.dataManagement.levelsCompleted;
for (int row = 0; row <= maxRows; row++)
{
for (int col = 0; col < maxCols; col++)
{
if (buttonNum < levelsCreated)
{
buttonNum += 1;
GameObject button = Instantiate(buttonTemplate);
button.SetActive(true);
button.transform.SetParent(parent.transform, false);
button.name = "Button" + buttonNum;
GameObject.Find(button.name).GetComponentInChildren<TextMeshProUGUI>().text = buttonNum.ToString();
pos.x = col * spacing.x + offset.x;
pos.y = row * -spacing.y + offset.y;
button.transform.localPosition = pos;
if (buttonNum > activeButtons && buttonNum != 1)
{
button.GetComponent<Button>().interactable = false;
}
}
}
DataManagement.dataManagement.SaveData();
}
}
private void CalculateSpacing()
{
rectTransform = GetComponent<RectTransform>();
float width = rectTransform.sizeDelta.x;
float height = rectTransform.sizeDelta.y;
spacing.x = width / 4;
spacing.y = height / 4;
offset.x = -width / 2;
offset.y = -height / 2;
Debug.Log(spacing);
}
Comment