Search Unity

Bug with onClick.AddListener

Discussion in 'Scripting' started by n3v3r001, Nov 27, 2015.

  1. n3v3r001

    n3v3r001

    Joined:
    Nov 16, 2014
    Posts:
    20
    It looks like i found a bug. Do you also have the same problem?

    Demo Script: "PlayerAttackHandling"
    public void StartAttack(int id)
    {

    Debug.Log("starting event for player attack " + id);
    }

    Demo code in another script:
    PlayerAttackHandling pah = newPlayer.GetComponent<PlayerAttackHandling>();
    for (int i = 0; i<PlayerAttackButtonArray.Length; i++)
    {

    Debug.Log("set button listener" + i);
    PlayerAttackButtonArray.onClick.AddListener(() => pah.StartAttack(i));

    }

    I have 2 Buttons in this Test Scenario.
    If i now klick the button0, it will write "id 2". But it should have id 0.
    If i change it like the following lines, it will just work.
    So i think thats a bug?


    for (int i = 0; i<PlayerAttackButtonArray.Length; i++)
    {

    Debug.Log("set button " + i);
    int test = i;
    PlayerAttackButtonArray.onClick.AddListener(() => pah.StartAttack(test));

    }
     
    Last edited: Nov 27, 2015