Skip to main content

unity event (runTime only) need help to change the object programatically




  • Alexandru Mares



    You can add UnityEvents programmatically quite easy. And here is how it's done:

    1. You need a reference to your UIButton

    public UIButton myButton;

    2. In your script you probably have a method you would like to have triggered when the method is invoked. So:

    public void MyMethod() { 


    3. Add your listener for the UnityEvent

    void OnEnable()
    { myButton.OnClick.AddListener(() => MyMehod());

    4. Make sure you also remove your listener if you disable the object resides on

    void OnDisable()
    { myButton.OnClick.RemoveListener(() => MyMehod());


    Finally here is the entire custom script:

    using UnityEngine;
    using DoozyUI;

    public class MyScript : MonoBehaviour
        public UIButton myButton; //reference to the target UIButton

        private void OnEnable()
            myButton.OnClick.AddListener(() => MyMethod()); //add a listener to the OnClick UnityEvents list of the target UIButton myButton

        private void OnDisable()
            myButton.OnClick.RemoveListener(() => MyMethod()); //remove a listener from the OnClick UnityEvents list of the target UIButton myButton (you need to remove this if it's no longer need as this is good code practice)

        private void MyMethod()
            //you can do anything here


    Did this help you out?

  • Mabiala Emile

    Thank you so much and yes it helped me a lot  I had found another way but this one is easier.


Please sign in to leave a comment.

Powered by Zendesk