Custom onClick list

Viewed 200

Can i create custom region with grouped methods for list onClick like dynamic and statics? like this

2 Answers

Yes and no! ^^

  • Yes, you can create your own event type taking a parameter and assign dynamic callbacks to it. What you are looking for is UnityEvent.

    For the dynamic parameterized ones see UnityEvent<T0> to UnityEvent<T0, T1, T2, T3> depending on how many parameters you need.

    For the example with a single int it would be (exactly as in the API example)

    // Since Unity doesn't support direct serialization of generics you have to implement this [Serializable] wrapper
    [Serializable]
    public class MyIntEvent : UnityEvent<int>
    {
    }
    
    public class ExampleClass : MonoBehaviour
    {
        public MyIntEvent m_MyEvent;
    }
    

    enter image description here

  • No, you can not simply change the existing implementation of UI.Button.onClick which is parameterless.

    What you could do, however, is build a new component and attach it on a button like

    [RequireComponent(typeof(Button))]
    public class ExampleClass : MonoBehaviour
    {
        [SerializeField] private Button _button;
        public MyIntEvent onClickWithIntParameter;
    
        private void Awake()
        {
            if(!_button) _button = GetComponent<Button>();
            _button.onClick.AddListener(HandleOnClick);
        }
    
        private void HandleOnClick()
        {
            // Wherever you get your int from
            var value = 123;
    
            onClickWithIntParameter.Invoke(value);
        }
    }
    

In the case that [Serializable] isn't working for you try [System.Serializable] or using System; at the top.

Related