Create 2 buttons one next to the other

Hi all,
i would like to create 2 buttons, one next to the each other.

For now my code is like this:

virtual protected void Start()
    {
        this.MoneyController = new MoneyController();
        this.createButtons();
    }

    virtual public void createButtons()
    {
        this.moneyButton = (GameObject)Instantiate(buttonPrefab);
        this.moneyButton.transform.SetParent(this.transform);
        this.moneyButton.transform.position = this.transform.position;
        this.moneyButton.GetComponent<Button>().onClick.AddListener(this.MoneyOnClick);
        this.UpdateMoneyButtonText();

        this.upgradeButton = (GameObject)Instantiate(buttonPrefab);
        this.upgradeButton.transform.SetParent(this.transform);
        this.upgradeButton.transform.position = this.moneyButton.transform.position;
        this.upgradeButton.transform.position = new Vector3(-this.moneyButton.GetComponent<RectTransform>().rect.width - 15, 0, 0);
        this.upgradeButton.GetComponent<Button>().onClick.AddListener(this.UpgradeOnClick);
        this.UpdateUpgradeButtonText();
    }

But doesn’t work like i would. One button has the correct position, the second one is out of the screen instead.

Sorry if the question is pretty stupid, i started today with unity and i need to learn a lot of things!

Thanks,
Davide.

Even with only two buttons I would suggest using HorizontalLayoutGroup or VerticalLayoutGroup.

https://docs.unity3d.com/ScriptReference/UI.HorizontalLayoutGroup.html

Here’s an exemple to implement it based on your code:

virtual protected void Start()
{
	this.MoneyController = new MoneyController();
	this.CreateHorizontalLayout();
	this.createButtons();
}

private void CreateHorizontalLayout()
{
	HorizontalLayoutGroup hlg = this.gameObject.AddComponent<HorizontalLayoutGroup>();
	hlg.childControlHeight = true;
	hlg.childControlWidth = true;
	hlg.childForceExpandHeight = true;
	hlg.childForceExpandWidth = true;
	hlg.padding = new RectOffset(3, 3, 3, 3);
	hlg.spacing = 3;
}

virtual public void createButtons()
{
	this.moneyButton = (GameObject)Instantiate(buttonPrefab);
	this.moneyButton.transform.SetParent(this.transform);
	// Not needed anymore: this.moneyButton.transform.position = this.transform.position;
	this.moneyButton.GetComponent<Button>().onClick.AddListener(this.MoneyOnClick);
	this.UpdateMoneyButtonText();

	this.upgradeButton = (GameObject)Instantiate(buttonPrefab);
	this.upgradeButton.transform.SetParent(this.transform);
	// Not needed anymore: this.upgradeButton.transform.position = this.moneyButton.transform.position;
	// Not needed anymore: this.upgradeButton.transform.position = new Vector3(-this.moneyButton.GetComponent<RectTransform>().rect.width - 15, 0, 0);
	this.upgradeButton.GetComponent<Button>().onClick.AddListener(this.UpgradeOnClick);
	this.UpdateUpgradeButtonText();
}