How to access the OnClick event via Script

I am trying to do a SongManager object which will be responsible for changing songs. I created a SongManager and a Song script. On runtime SongManager creates as many song buttons as i want each with different variables. Everything seems to work fine except that i cant get to OnClick event to change the songs.I tried many things but i guess its all outdated. Stuff like:

 public Button.ButtonClickedEvent OnClickEvent;

or

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

Appreciate any help, thank u guys.


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

public class SongManager : MonoBehaviour {

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

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

void Start ()
{
    FillList();
}

void FillList()
{
    foreach (var song in songList)
    {
        GameObject newButton = Instantiate(button) as GameObject;
        SongButton songButton = newButton.GetComponent<SongButton>();
        songButton.songName.text = song.SongName;
        songButton.clip = song.clip;

        newButton.transform.SetParent(panel, false);
    }
}

}

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

public class SongButton : MonoBehaviour
{
    public Text songName;
    public int unlocked;
    public AudioClip clip;
}

Second piece of code isn’t outdated. OnClick is event so you need to use it like event.
First of all you must have method what you want use in OnClick event, as example is method below enough :

void Clicked (int unUsedNumber)
{
       Debug.Log("You click button, why?")
}

Next you need to get references Button component of this gameobject. You need to listen through listener, so you must add the listener. Using lambada use any function as argument. This function still can have its own argument(like int unUsedNumber)

gameObject.GetComponent<Button>().onClick.AddListener(() => Clicked(6));

Now every time you click button, unity Editor ask why you click button,of course you can use any method… may be something more useful :slight_smile: