Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

Adding Listener when instantiating objects

Discussion in 'Scripting' started by Davi_J, Dec 6, 2018.

  1. Davi_J

    Davi_J

    Joined:
    May 18, 2014
    Posts:
    3
    I've found a few posts on similar issues, but haven't been able to find a solution, and I'm not getting any errors, just not getting any events to occur. Right now my method "ChooseCharacterAndLoadGame()" is just writing to the console, but it doesn't seem to be called. I am getting the debug message that the button was found and not null, but the onClick doesn't seem to be getting set. Any suggestions on where to find my problem?

    Code (CSharp):
    1.  void InitializeCharacters()
    2.     {
    3.         int index = 0;
    4.         for (int i = 0; i < CharacterList.Length; i++)
    5.         {
    6.             GameObject obj = Instantiate(CharacterList[index], new Vector3((i+-2) * 2.0F, transform.position.y, 2), Quaternion.identity) as GameObject;
    7.             Button characterButton = obj.GetComponent<Button>();
    8.  
    9.             if (characterButton != null) {
    10.                 characterButton.onClick.AddListener(() => ChooseCharacterAndLoadGame());
    11.                 Debug.Log("Button not null " + obj);
    12.             }
    13.            
    14.             index++;
    15.  
    16.             if (index == CharacterList.Length) { index = 0; }
    17.         }
    18.     }