如何通过脚本访问 OnClick 事件

How to access the OnClick event via Script

我正在尝试创建一个负责更改歌曲的 SongManager 对象。我创建了一个 SongManager 和一个 Song 脚本。在运行时 SongManager 创建尽可能多的歌曲按钮,每个按钮都有不同的变量。一切似乎都很好,除了我无法进入 OnClick 事件来更改 songs.I 尝试了很多东西,但我想它都已经过时了。像这样的东西:

public Button.ButtonClickedEvent OnClickEvent;

go.GetComponent<Button>().onClick.AddListener();

感谢任何帮助,谢谢你们。

您将函数名称传递给 AddListener 参数。

public GameObject go;
Button myButton = null;

void Start()
{
    myButton = go.GetComponent<Button>();
    myButton.onClick.AddListener(() => myCallBackFunction());
}

void myCallBackFunction()
{
    Debug.Log("Button Clicked!");
}

您还可以这样做:myButton.onClick.AddListener(delegate { myCallBackFunction(); });

注:

下次请 post 您的代码,而不是 post 截图。

您可以使用 Events 与您的其他 类 进行交流。这是代码:

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

public class SongButton : MonoBehaviour {

    public delegate void SongButtonEvent(int index);
    public static event SongButtonEvent OnSongButtonClick;
    void ClickSongButton(){
       if (OnSongButtonClick != null)
            OnSongButtonClick (index);
    }

    public Button button;
    public Text songName;
    public int unlocked;
    public AudioClip clip;
    public int index;

    void Start () {
        button.onClick.AddListener (ClickSongButton);
    }

    public void Initialize(int index,Song song){
        this.index = index;
        songName.text = song.songName;
        unlocked = song.unlocked;
        clip = song.clip;
        button.interactable = song.isInteractable;
    }
}

首先,我创建了一个 Initialize 方法。它使用 Song 对象变量进行初始化,并将索引作为按钮 ID。在我为带有索引的通知侦听器创建事件之后。

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;

[System.Serializable]
public class Song
{
    public string songName;
    public int unlocked;
    public bool isInteractable;
    public AudioClip clip;
}

public class SongManager : MonoBehaviour
{

    public SongButton button;
    public Transform panel;
    public List<Song> songList;

    void OnEnable(){
        SongButton.OnSongButtonClick += SongButton_OnSongButtonClick;
    }

    void OnDisable(){
        SongButton.OnSongButtonClick -= SongButton_OnSongButtonClick;
    }

    void SongButton_OnSongButtonClick (int index)
    {
         Debug.Log ("index : " + index + " - song name : " + songList [index].songName);
    }

    void Start ()
    {  
       FillList ();    
    }

    void FillList ()
    {  
        for (int i = 0; i < songList.Count; i++) {
            SongButton songButton = Instantiate (button) as SongButton;  
            songButton.Initialize (i, songList [i]);
            songButton.transform.SetParent (panel, false);
        } 
    }
}

当SongManager 启用后,它开始监听OnSongButtonClick 事件。这样,您就可以知道点击了哪个按钮。

希望对您有所帮助。