Balalaika Balalaika - 1 month ago 12
C# Question

C# Unity Wrong argument of the function in onClick event

When I'm adding methods to

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

all_buttons
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...");
Application.LoadLevel(level);
}

Answer

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));
Comments