Hi I am trying to pass a method to an add listener when the button is clicked. First I instantiated the object and assign a parent for it. Then I add a listener to the object. The problem is that the only way I know how to pass a method with parameter in the add listener event of unity is through lambda expression. So when I click the button it always passes the last item I iterated to.
Here is a snippet of my code:
foreach(CardData cardItem in p_cards)
{
if(cardItem.Type == CardType.Normal)
{
if(count == 0)
{
cardItem.Name = "CARD ONE";
}
else{
cardItem.Name = "CARD TWO";
}
GameObject m_card = Instantiate(m_regularDetailCard) as GameObject;
m_card.transform.SetParent(m_detailCardContainer.transform);
m_card.GetComponent<RectTransform>().SetDefaultScale();
m_card.GetComponent<Button>().onClick.AddListener(() => {InitializeCardScreen(cardItem);});
}
count++;
}
So what happens is that the parameter I passed in my InitializeCardScreen method will always be “CARD TWO” since it is the last object I instantiated and also since lambda only assigns the value of cardItem when the event onClick is triggered.
Is there any work around for this problem aside for creating ids for each instantiated item?