add delegate to toggle in unity 4.6 UI

i know i can set action “Onclick” for button with delegate.
so how do i apply delegate for the toggle component? i don’t have OnClick for it. only onValueChanged.
i’m adding toggles to panel with script and need to set each toggle the relevant index for “updateVehicleDisplay”.

so i tried:

toggleScript.toggle.onValueChanged.AddListener(delegate {updateVehicleDisplay(i);});

and i have:

public void updateVehicleDisplay( int  index){
        Debug.Log (vehicleList[index].name);

i don’t get compile error, but nothing is happen when i click the toggle.


Sorry @haim96 being an idiot and trying to answer things on my phone when I can’t even read the full post.

Got this working with this code:

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

public class DelegateToggle : MonoBehaviour {

	public GameObject prefabToggle;
	public RectTransform ParentPanel2;

	// Use this for initialization
	void Start () {

		for(int i = 0; i < 5; i++)
			GameObject goToggle = (GameObject)Instantiate(prefabToggle);
			goToggle.transform.SetParent(ParentPanel2, false);
			goToggle.transform.localScale = new Vector3(1, 1, 1);
			Toggle tempToggle = goToggle.GetComponent<Toggle>();
			int tempInt = i;
			tempToggle.onValueChanged.AddListener(delegate {ToggleClicked(tempInt);});
	// Update is called once per frame
	void ToggleClicked (int toggleNo) {
		Debug.Log ("Toggle changed = " + toggleNo);

There’s an issue with C# holding the temp value i on loops that I believe is fixed in 5 but not 4.6. If you set a temp int to hold i it works. That’s probably your issue but I can get it to output which number was clicked with the code above.


Not sure, my code works but you will have to set the parent panel to have a Vertical layout Group and untick force expand at least on height. Then add a layout element to the prefab toggle and set the minimum height to something like 30.

Create a test canvas and put my code on there, drag in a toggle prefab and parent panel to the script, hey you’ve got 2k karam! I don’t need to tell this :¬) all I’m saying is test my code as is and see what results you get.

Instead of creating delegate most simplest and easiest way would be to create an event, you can register event in any class and it will be executed when when your desired event occurs.