Problem using array element as parameter in AddListener callback function

OK the title may sound a little bit confusing so here’s some source code

private int[] myArray = new int[2];
myArray[0] = 1;
myArray[1] = 2;

public Button myButton; // to be assigned in the inspector
myButton.onClick.AddListener(() => { DisplayNumber(myArray[0]);});

This is quite simple: create a button, add a listener so that it will call the DisplayNumber function when clicked. However everytime pressing the button I got the following error:

IndexOutOfRangeException: Array index is out of range.
RandomNumber+c__AnonStorey0.<>m__1 () (at Assets/Script/QuickSort/RandomNumber.cs:44)
UnityEngine.Events.InvokableCall.Invoke (System.Object[ ] args) (at C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/UnityEvent.cs:109)
UnityEngine.Events.InvokableCallList.Invoke (System.Object[ ] parameters) (at C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/UnityEvent.cs:577)
UnityEngine.Events.UnityEventBase.Invoke (System.Object[ ] parameters) (at C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/UnityEvent.cs:717)
UnityEngine.Events.UnityEvent.Invoke () (at C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/UnityEvent_0.cs:53)
UnityEngine.UI.Button.Press () (at C:/BuildAgent/work/d63dfc6385190b60/Extensions/guisystem/guisystem/UI/Core/Button.cs:35)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/BuildAgent/work/d63dfc6385190b60/Extensions/guisystem/guisystem/UI/Core/Button.cs:44)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/BuildAgent/work/d63dfc6385190b60/Extensions/guisystem/guisystem/EventSystem/ExecuteEvents.cs:52)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/BuildAgent/work/d63dfc6385190b60/Extensions/guisystem/guisystem/EventSystem/ExecuteEvents.cs:269)
UnityEngine.EventSystems.EventSystem:Update()

The solution (after painful hours searching testing and trying stupid attempts), is to not assign directly the array element into the callback function, but using a temporary variable instead:

private int[] myArray = new int[2];
myArray[0] = 1;
myArray[1] = 2;

public Button myButton; // to be assigned in the inspector
int myNumber = myArray[0];
myButton.onClick.AddListener(() => { DisplayNumber(myNumber);});

This maybe a work around for those who want to generate button by script (like level selection) in case you guys meet the same problem, and this is odd though.

I’m using 4.6.0b20

6 Likes

THANK YOU! I don’t want to know how many hours of head banging you saved me, there…

1 Like

This was exactly what I needed. Why is this information not everywhere that buttons and scripts are!?
Thanks for the solution to this headache.

1 Like

Thank you very much for this hint ! +D