onClick listener delegation on UI Button

14,887

Solution 1

The problem i was facing is that my Button was conflicting with a custom class i made called Button.cs. Now i've learned not to use Class names that already exist in the environment^^

fixed it with the direct path to the Class:

UnityEngine.UI.Button btn = newButton.GetComponent<UnityEngine.UI.Button>();
btn.onClick.RemoveAllListeners(); 
btn.onClick.AddListener(() => placeBuilding(obj.name));

code:

GameObject button = Resources.Load <GameObject>("Button"); //loading from resource

GameObject newButton = Instantiate(button);
newButton.transform.parent = panel.transform;
newButton.GetComponentInChildren<Text>().text = obj.name;
newButton.transform.position = button.transform.position;
newButton.transform.position += new Vector3(20*x, -70 * z, 0);
UnityEngine.UI.Button btn = newButton.GetComponent<UnityEngine.UI.Button>();
btn.onClick.RemoveAllListeners(); 
btn.onClick.AddListener(() => placeBuilding(obj.name));

This code is inside a loop

Solution 2

Well I got something working, that might suits your needs.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class MainLab : MonoBehaviour, IPointerClickHandler {

// Use this for initialization




    void Start () {

}



    public void OnPointerClick(PointerEventData eventData)
    {

        Debug.Log("Hello");
    }
}

In this we added, UnityEngine.EventSystems and then added the Interface IpointerClickHandler. FYI you can also add Drag or whatever interface you may want.

then just and the the method interface. RightClick the IPinterClickHandler then choose Implement Interface to check what other method it has.

You would need to attach this to a gameObject. ANY GameObject. Including buttons.

So Dynamically in your List of Buttons, either you want to add this as a component. AddComponent(); I call my class MainLab for testing purposes.

Share:
14,887
nkmol
Author by

nkmol

Belief makes possible

Updated on June 04, 2022

Comments

  • nkmol
    nkmol almost 2 years

    So since 4.6 unity uses a new UI system, what i never used. Until now.

    What I'm trying to do is generating buttons in a dynamic way, thus I also have to add the onClick event in a dynamic way (or atleast through scripting).

    I've tryed to extend the onClick Listener, but it doesn't want to work:

    btn.GetComponent<Button>().onClick.AddListener(() => { placeBuilding(obj.name); });
    

    It will give this error which does sounds pretty clear in what is wrong:

    Assets/Scripts/Menu/btnBouwen.cs(72,45): error CS0119: Expression denotes a 'method group', where a 'variable', 'value' or 'type' was expected

    However I have no idea how to use an UnityAction as it seems the required type for the call.

    Feels like I'm missing something really easy. Hope somebody can help me.

    Kind regards, Nkmol