-
-
Save elenzil/63353fe22ba8d588e5cad8a2c63a83be to your computer and use it in GitHub Desktop.
Improved ToggleGroup for Unity GUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
using UnityEngine.UI; | |
// based on https://gist.github.com/jmbeach/78c3e46669db89628fce | |
public class BetterToggleGroup : ToggleGroup { | |
public Action<Toggle> OnChange; | |
protected override void Start() { | |
base.Start(); | |
ManageListening(true); | |
} | |
private void ManageListening(bool listen) { | |
int count = 0; | |
foreach (Transform transformToggle in gameObject.transform) { | |
count += 1; | |
Toggle toggle = transformToggle.gameObject.GetComponent<Toggle>(); | |
if (listen) { | |
toggle.onValueChanged.AddListener(OnTog); | |
} | |
else { | |
toggle.onValueChanged.RemoveListener(OnTog); | |
} | |
} | |
if (count == 0) { | |
Debug.LogWarning("No Toggles found in Children. Is your scene set up correctly ?"); | |
} | |
} | |
private void OnTog(bool isSelected) { | |
if (isSelected) { | |
if (OnChange != null) { | |
OnChange(FirstActiveToggle()); | |
} | |
} | |
} | |
public Toggle FirstActiveToggle() { | |
foreach (Toggle t in ActiveToggles()) { | |
return t; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! I just want to make an edit that current version of Unity has
toggleGroup.GetFirstActiveToggle()
functionAnd the other is to add
OnDestroy