0

In my application I have a list of GameObject's, and I'm creating a button for each GameObject in the list via code. The problem is that when I add and onClick Event via code nothing shows up in the button onClick list, nothing happens when I click the button and I get no errors in the process. Here is how my code looks like:

   public GameObject prefab;

   public void Generate()
    {
        for (int i = 0; i < myList.Count; i++)
        {
            GameObject _t = Instantiate(prefab, myUIPanel.transform) as GameObject;

            //Positioning, naming, ...

            _t.GetComponent<Button>().onClick.AddListener(delegate { MyFunction(i); });
        }
    }

public void MyFunction(int index)
{
    //...
}

I've created a GUILayout.Button inside an editor script to call the "Generate" method. The buttons are created and I get no errors, but no Event is added in the buttons.

Gregor Sattel
  • 352
  • 3
  • 12

1 Answers1

0

edit: because you ui element is being instantiated from the prefab the button is not hooking up to EventSystem

workaround: use scriptableobject instead of monobeviour, scriptableobjects work independent from scene/gameobject instances

tutorial: https://docs.unity3d.com/Manual/class-ScriptableObject.html

https://www.raywenderlich.com/2826197-scriptableobject-tutorial-getting-started

vasmos
  • 2,472
  • 1
  • 10
  • 21
  • It's not missing the component. I've added a debug message and the component is there. I'm also sure the component is attached to the object i'm referencing with _t and not it's children, so changing to GetComponentInChildren didn't fix it as well. – Gregor Sattel May 06 '20 at 17:10
  • I added my answer for a possible workaround / something to test – vasmos May 06 '20 at 17:25
  • It's not the argument, but for some reason the whole AddListener function does not work and I have no clue why. I event created UnityAction instance and still nothing. – Gregor Sattel May 06 '20 at 17:37
  • Okay I edited my answer, I think the button just because its being instantiated as a prefab is not being registered in the ui event system, I would recommend checking out scriptableobjects – vasmos May 06 '20 at 17:50