Unity3d Associate an action with a different parameter (incremented index) to a button prefab
<p>I'm having a button prefab so i tried to associate  a scene object script to it , which i guess is not possible , but now i'm trying to associate a button click action to a dynamically created button in some script , here is the code snippet.  </p>

<pre><code>int index = 0 
    public IEnumerator GenerateItems()
        {

    foreach (ArrayList eat in eatArray))
    {
        Debug.Log (index);


        GameObject localItem = (GameObject)Instantiate(item, Vector3.zero, Quaternion.identity);

        UnityEngine.Events.UnityAction action = () =&gt; {  Debug.Log(index); };
        ++index;


        localItem.GetComponent&lt;Button&gt;().onClick.AddListener(action);
        localItem.transform.SetParent(grid.transform);
        localItem.transform.localScale = autoLocalScale;
        localItem.transform.localPosition = Vector3.zero;

    }
    yield return new WaitForSeconds(.1f);




    ///1. Two ways to move the scroll to first item
    scrollRect.horizontalNormalizedPosition = 0;

    //      //2. Moving the scroll bar to left
    //      //scrollBar.value = 0;

}
</code></pre>

<p>What i get the value of index is 2 and i want that when i click on the indexed button (like 2 buttons are there so i should get 0  on the first buttons click and 1 on second buttons click ) . </p>

<p>The item is a prefab , contains a button component that I get by get component function and add action to the button .eatArray is also an arrayList. And I instantitate the item to localItem  giving it a position and so localItem is a gameobject with component button on it .eatarray is basically used to get the count number of times the loop runs</p>

<p>Edit : </p>

<pre><code>public void OnClick()
        {
         Debug.Log(index);
        }
</code></pre>

<p>I can get the correct index value when i attach the script on button prefab with the index variable in it and I increment the index in the for loop as</p>

<pre><code>   localItem.GetComponent&lt;GridButton&gt; ().index = index++;
</code></pre>

<p>and now  this OnClick() function does return correct index but i can't do it this way because there are lot of functions written on other script and i don't want to duplicate code and can't use reference cause many functions are private. </p>