Hello there. I have searched for an answer to this but can’t find anyone with my specific problem.
I am populating an array of buttons in a vertical layout, the data coming from scriptable objects. I am trying to add unique listeners to each button. When I run the code, the buttons ALL have the information from the last scriptable object in the list. The buttons are supposed to add or subtract values depending on which one you pick.
Here is my code. I think the problem is with newObj.GetComponent.onclick.addlistener. It seems to be overriding all previous buttons with the latest version.
void Populate()
{
GameObject newObj;
int MoneyChange;
int FoodChange;
int HealthChange;
for (int i = 0; i < EarnMoneyOptions.Count; i++)
{
newObj = (GameObject)Instantiate(EarnOption, transform);
newObj.GetComponentInChildren<Text>().text = EarnMoneyOptions[i].description;
MoneyChange = EarnMoneyOptions[i].MoneyChange;
FoodChange = EarnMoneyOptions[i].FoodChange;
HealthChange = EarnMoneyOptions[i].HealthChange;
newObj.GetComponent<Button>().onClick.AddListener(() => ButtonClicked(MoneyChange, FoodChange, HealthChange));
Debug.Log("Populate Script: " + EarnMoneyOptions[i].MoneyChange);
}
}
void ButtonClicked(int MoneyChange, int FoodChange, int HealthChange)
{
Debug.Log(MoneyChange + " " + HealthChange);
PlayerPrefs.SetInt("Health", PlayerPrefs.GetInt("Health") + HealthChange);
PlayerPrefs.SetInt("Money", PlayerPrefs.GetInt("Money") + MoneyChange);
PlayerPrefs.SetInt("Food", PlayerPrefs.GetInt("Food") + FoodChange);
}