- Home /
How can I instantiate a button prefab, complete with onClick() method, at runtime?
Background: I am making a tower defense game, and I want to be able to switch out the buttons for each level, without making a new scene for each level. Basically, I want to be able to say, in code, "When you load this level, in addition to setting up the enemy spawning, create 4 buttons that the player can click to place towers", and have me, the programmer be able to set those 4 towers to different ones for different levels.
So I need button prefabs for all of them, and I need to instantiate them at runtime, and get them to each run a method (see code) that has unique arguments (tower type, cost) when clicked.
Here's my code so far:
public class BuyDragable : MonoBehaviour {
public GameObject drag;
public int cost;
// Use this for initialization
public void BuyStuff()
{
if (GameObject.FindObjectOfType<ScoreManager> ().SpendDna (cost))
{//checks to see if the player has enough money to buy it
Instantiate(drag, this.transform.position, this.transform.rotation);
}
}
}
This script is attached to my button, and is set to run OnClick() (see picture.) What I want to do is create several prefabs which I can instantiate, which have the same script (BuyDragable), but have different parameters (the cost of the tower, and the tower object itself). The different buttons also need to have different pictures.
So how is the best way to do this? Can I instantiate these prefabs through code, and how? Would it be easier to place the button prefabs in the scene before runtime, and just set the button image, tower object, and cost of tower at runtime? How would I do that?
Thanks!
Use AddListener:
myButton.onClick.AddListener(delegate{YourFunction(Parameter);});
to assign an OnClick event.
Remember to use RemoveAllListeners when you add a new one if you don't want multiple events.
Answer by Cynikal · Jul 16, 2017 at 07:25 PM
You could always do it the old fashioned way and create a script where when it's clicked on that it triggers the command you want.
But how do I give the script different values at runtime? For example, sometimes calling the script and sending it one tower prefab and int cost, and other times calling it with another tower prefab and a different cost?
Because the only way I know how to change the values that the script takes is through the inspector, and I obviously can't use that to change them at runtime.
Your answer
![](https://koobas.hobune.stream/wayback/20220612130421im_/https://answers.unity.com/themes/thub/images/avi.jpg)