Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Button OnClick has the empty list after Button create script running.

Discussion in 'UGUI & TextMesh Pro' started by sangkfb, Sep 3, 2023.

  1. sangkfb

    sangkfb

    Joined:
    Aug 18, 2021
    Posts:
    3
    I can manually add OnClick listener to the button on Unity Editor and it works well.
    I now need to do this programatically.

    Below is my test code.
    After running this, I see it created "MyButton" GameObject and a Button component inside.
    Also it found the existing "MyScript" component.
    But it has the empty list of "On Click()" at Button component on Unity Editor.
    I followed this instruction.
    How can I add On Click listener from the script?

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3.  
    4. public class TestEditor : Editor
    5. {
    6.     [MenuItem("Edit/Test")]
    7.     private static void Test()
    8.     {
    9.         GameObject buttonObject = new GameObject("MyButton");
    10.         var button = buttonObject.AddComponent<UnityEngine.UI.Button>();
    11.  
    12.         var script = GameObject.Find("ObjWithScript").GetComponent<MyScript>();
    13.         button.onClick.AddListener(() => script.ButtonClicked());
    14.         button.onClick.AddListener(delegate {script.ButtonClicked();});
    15.         button.onClick.AddListener(script.ButtonClicked);
    16.     }
    17. }
     
  2. bugfinders

    bugfinders

    Joined:
    Jul 5, 2018
    Posts:
    711
    have you tried setting the scene dirty after setting the listener?
     
  3. sangkfb

    sangkfb

    Joined:
    Aug 18, 2021
    Posts:
    3
    I tried below after setting the listener and still see the empty listener.

    Code (CSharp):
    1.         EditorUtility.SetDirty(button);
    2.         EditorUtility.SetDirty(buttonObject);
    3.         EditorApplication.MarkSceneDirty();
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    sangkfb likes this.
  5. sangkfb

    sangkfb

    Joined:
    Aug 18, 2021
    Posts:
    3