Hello, I’m trying to add an onclick event on a button in a prefab (and then instantiate it).
The problem is that everything works except for the onclick event.
I made sure that nothing covers the button (so the problem must be code related).
Here’s an example of the event add:
rankPrefab.transform.GetChild(1).GetComponent<Button>().onClick.AddListener(
() => SetRewardsAndOpen(ranks[i], ranks[i-1])
);
(the if(i==0) is alreay managed)
Everything is in a for loop to set up every prefab part and instantiate.
The function SetRewardsAndOpen should open the rewards for a specific rank and everything is already set up.
The ranks[i] is a List of a Scriptable Object.
1 Answer
1
Hello @loller97,
I see many problems in your code:
- Don’t change a prefab
- Adding a function on a listener will add the address of the function same for variables so if you add “i” it will add the address and not the value, so if your loop continues then when your callback will be invoked it will use the current value of “i”, to fix this you can use a temporary variable:
for (int i = 0; i < thingy; i++) {
int j = i;
button.onClick.AddListener(() => MyFunction(j)); // I now use "j" which is the current value of "i"
}
- Avoid Searching for a component in a child like this, it’s better to directly have a reference on the button or use the function GetComponentInChildren<Button>(), because if you change the children order you’ll break your code
I hope it helps