I am making an inventory system, so I want each button onClick to call a function with a unique integer per button, so it knows which slot is being clicked. Below is my code:
public int inventorySize = 32;
public GameObject slotPrefab;
public GameObject slotHolder;
private int curSlotId = 0;
public void InitiateMenu()
{
inventory.Initialize();
for (int i = 0; i < inventorySize; i++)
{
GameObject newSlot = Instantiate(slotPrefab);
newSlot.transform.SetParent(slotHolder.transform, false);
//Change onClick
newSlot.GetComponent<Button>().onClick.AddListener(delegate { SlotClick(curSlotId); });
curSlotId++;
}
}
public void SlotClick(int slot)
{
Debug.Log("Inventory Slot #" + slot.ToString());
}
Whatever I do, it seems that all buttons when clicked write “Inventory Slot #32” to the Debug.Log, I have tried using just the i variable in the for loop, which warranted the same issue. How would you go about doing this? It seems however I initiate or place the variable it reads the same memory space every single for loop, making all the buttons call the function with the integer 32.
I know many people don’t like when Unity questions are asked with the ‘C#’ tag but I wonder if this is a C# thing, not a Unity thing. Please excuse me if I am wrong.