- Home /
A Problem with button listener in Start()
Hello I have a Button prefab which I want to assign different methods for it depends on some condition but when I add my code to Start() it get called once. and If I add it to update it gets called a lot of time which crashes the application here is my code: void Start () {
if (Pick1)
{
Power1 = Instantiate(b, panel.transform, true) as GameObject;
//GUI adjustment
Power1.transform.localScale = new Vector3(1, 1, 1);
Power1.transform.position = new Vector3(0, 0, 100);
Power1.GetComponent<Button>().onClick.AddListener(() => Freeze());
}
}
Freeze() method only getting called 1 time no matter how many times I press the button any suggestion please?
If you add listener in the start then AddListener only call one time because start calls only once. Lets suppose you want to add listener again when object triggers, then you need to remove all listeners and then again add new listener.
void Start ()
{
btn.onClick.AddListener(Func1);
}
void OnTriggerEnter()
{
btn.onClick.RemoveAllListeners();
btn.onClick.AddListener(Func2);
}
void Func1()
{
Debug.Log("func1");
}
void Func2()
{
Debug.Log("func2");
}
This should work, what exactly does Freeze() do? Perhaps it is something in the Freeze() method that affects the button? Also no need for a lambda, you can just assign it like this
Power1.GetComponent<Button>().onClick.AddListener(Freeze);
I think the lambda might be your issue, since it compiles differently.
Your answer
Follow this Question
Related Questions
Weird behaviour when trying to dynamically create buttons 0 Answers
My onclick action listeners I attach to my buttons as I instantiate them only work once 1 Answer
Link variables of a script in dynamically instantiated prefab before start is called 1 Answer
GUI Creates a prefab? 1 Answer
Using a prefab button 0 Answers