In the script below, "btn" is a local variable in OnEnable() method. It's said that local variable is deallocated (lost) when leaving the countaining method. Why this one (btn) is not ? Nb: when the game is running and Button is clicked (OnClick) method is called
using UnityEngine.ui;
List<Button> _answers;
public List<Button> Answers { get { return _answers; } }
[SerializeField] Button buttonPrefab;
private void OnEnable()
{
CreateAnswerButtonPool();
for (int i = 0; i < Answers.Count; i++)
{
Button btn = Answers[i];
btn.onClick.AddListener(() => OnClick(btn));
}
}
private void CreateAnswerButtonPool()
{
_answers = new List<Button>();
for (int i = 0; i < 5; i++)
{
Button bt = Instantiate(buttonPrefab, buttonsparent.transform) as Button;
bt.gameObject.SetActive(false);
_answers.Add(bt);
}
}
void OnClick(Button btn)
{
//.....
}