Balalaika Balalaika - 1 year ago 238
C# Question

C# Unity Wrong argument of the function in onClick event

When I'm adding methods to

buttons the argument of the function is always
const = array of buttons.length + 1
. Where did I go wrong?

not empty. I clicked on three different buttons.
Unity log screenshot: link

Button[] all_buttons = GetComponentsInChildren<Button>();
for (int i = 0; i < all_buttons.Length; i++) {
Debug.LogWarning(all_buttons[i]+" => addLoad with index "+ (m_LvlStartIndex + i));
if (levelScript)
all_buttons[i].onClick.AddListener(() => Load(m_LvlStartIndex+i));

public void Load(int level) {
Debug.LogWarning("Loading "+level+" level...");

Answer Source

The problem is on this line of code:

all_buttons[i].onClick.AddListener(() => Load(m_LvlStartIndex+i));

You are supposed to save i to a temporary variable before using it with the AddListener function. The code below should fix it:

int tempI = i;
all_buttons[i].onClick.AddListener(() => Load(m_LvlStartIndex+tempI));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download