Mace_Craze
Mace_Craze

Reputation: 1

Setting an Instatiated button's OnClick, in order to set a gameobject variable? Unity C#

Hey guys! First time using Stack Overflow because of the unique nature of my problem.

I am currently instantiating a button based off of how many of a gameObjects with a certain script I have in the scene. How would I go about ensuring the instantiated Button's onClick, is setting the parent script's empty gameObject var is set to the (i) gameObject (the physical turret)?

private void Start()
{
    Turret_Script[] turretsOnTank = FindObjectsOfType<Turret_Script>();

    for (int i = 0; i < turretsOnTank.Length; i++)
    {
        GameObject turretButton = Instantiate(testingTurretButton, gameObject.transform.GetChild(0).GetChild(0).gameObject.transform);
        turretButton.transform.GetChild(0).GetComponent<Text>().text = turretsOnTank[i].name;
        turretButton.transform.position = new Vector3(150 + (100 * i), 330);

        //This is where I assume I'd make a button var based off of the turretButton var.

        //This is where I assume I'd change the OnClick of the button.
    }
}

Upvotes: 0

Views: 354

Answers (1)

MyBug18
MyBug18

Reputation: 2240

If the button you're using is Button, you can do it like this:

for (int i = 0; i < turretsOnTank.Length; i++)
{
    GameObject turretButton = Instantiate(testingTurretButton, gameObject.transform.GetChild(0).GetChild(0).gameObject.transform);
    turretButton.transform.GetChild(0).GetComponent<Text>().text = turretsOnTank[i].name;
    turretButton.transform.position = new Vector3(150 + (100 * i), 330);
    turretButton.GetComponent<Button>().onClick.AddListner(
        () => turretHolder = turretsOnTank[i]);
}

() => turretHolder = turretsOnTank[i] is the lambda which will set turretHolder field with turretsOnTank[i], which i is the index of turret.

By the way, your code looks like it needs some reforming. GetChild() returns transform, so you don't neet to do GetChild(0).gameObject.transform to get transform. Just GetChild(0) would enough.

And, transform field is already exists in MonoBehaviour, so you don't need to access transform via gameObject.

And, Instantiate can return Transform type, if prefab is Transform. So, your code would be:

    Transform turretButton = Instantiate(testingTurretButton.transform, gameObject.transform.GetChild(0).GetChild(0));
    turretButton.GetChild(0).GetComponent<Text>().text = turretsOnTank[i].name;
    turretButton.position = new Vector3(150 + (100 * i), 330);
    turretButton.GetComponent<Button>().onClick.AddListner(
        () => turretHolder = turretsOnTank[i]);

Which has more less redundancy.

Upvotes: 0

Related Questions