Skip to content

Instantly share code, notes, and snippets.

@elenzil
Forked from jmbeach/BetterToggleGroup.cs
Last active May 5, 2024 20:18
Show Gist options
  • Save elenzil/63353fe22ba8d588e5cad8a2c63a83be to your computer and use it in GitHub Desktop.
Save elenzil/63353fe22ba8d588e5cad8a2c63a83be to your computer and use it in GitHub Desktop.
Improved ToggleGroup for Unity GUI
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;
}
}
@elenzil
Copy link
Author

elenzil commented Mar 5, 2019

minor changes.

  • removed Linq.
  • simplified delegate by using System.Action.
  • fixed issue with Start() shadowing the base class's Start().

@cihadturhan
Copy link

Thank you! I just want to make an edit that current version of Unity has toggleGroup.GetFirstActiveToggle() function
And the other is to add OnDestroy

  private void OnTog(bool isSelected) {
    if (isSelected) {
      if (OnChange != null) {
        OnChange(GetFirstActiveToggle());
      }
    }
  }


 protected override void OnDestroy() {
    base.OnDestroy();
    ManageListening(false);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment