Search Unity

  1. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  2. Want more efficiency in your development work? Sign up to receive weekly tech and creative know-how from Unity experts.
    Dismiss Notice
  3. Participate with students all over the world and build projects to teach people. Join now!
    Dismiss Notice
  4. Build games and experiences that can load instantly and without install. Explore the Project Tiny Preview today!
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  6. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Adding Listener when instantiating objects

Discussion in 'Unity UI & TextMesh Pro' started by Davi_J, Dec 6, 2018 at 8:20 PM.

  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.     }