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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
I added my answer for a possible workaround / something to test
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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.