Search Unity

  1. Unity 2019.1 beta is now available.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. We're looking for insight from anyone who has experience with game testing to help us better Unity. Take our survey here. If chosen to participate you'll be entered into a sweepstake to win an Amazon gift card.
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Unity 2018.3 is now released.
    Dismiss Notice
  6. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice

Adding Listener when instantiating objects

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

  1. Davi_J


    May 18, 2014
    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>();
    9.             if (characterButton != null) {
    10.                 characterButton.onClick.AddListener(() => ChooseCharacterAndLoadGame());
    11.                 Debug.Log("Button not null " + obj);
    12.             }
    14.             index++;
    16.             if (index == CharacterList.Length) { index = 0; }
    17.         }
    18.     }