- Home /
Question by
m0nkeybl1tz · Mar 28, 2019 at 05:37 PM ·
c#event
Best way to implement a radio button style system (without using Unity UI)
I'm creating a menu system for our game, but rather than using a 2D menu it's all 3D buttons. For one menu I want to have it be a radio button-style selection system: if you click on one button, it automatically deselects all other buttons. I'm wondering if there's a best practice for implementing a system like this.
I figure you could have a button manager and have each button call a function on it when the button is clicked, telling it to uncheck every other button. However this would force each button to have a reference to the manager, so it feels kind of inelegant. Is there a better way? Maybe with an event system or something?
Thanks!
Comment
I could suggest an event system as you implied:
//This script is for observing radio button clicks. Attach this to any gameobject
public class ToggleEventSystem : $$anonymous$$onoBehaviour {
public delegate void radioToggleDelegate(RadioButton rb, bool b);
public static event radioToggleDelegate radioToggleEvent;
public static void RadioButtonToggled(RadioButton rb, bool b) {
if (radioToggleEvent != null) {
radioToggleEvent(rb, b);
}
}
private void Update() {
if (Input.touchCount > 0) { //i assume platform is mobile. You could use Input.mousePosition ins$$anonymous$$d if you work with standalone
RadioButton button = ControlHit(Input.GetTouch(0).position);
if (button != null) {
RadioButtonToggled(button, true);
}
}
}
private RadioButton ControlHit(Vector3 touchPos) {
Ray ray = Camera.main.ScreenPointToRay(touchPos);
RaycastHit hit;
Physics.Raycast(ray, out hit);
if (hit.collider != null) {
return hit.collider.gameObject.GetComponent<RadioButton>();
}
return null;
}
}
//this script here is base class for registering toggle events
public abstract class ToggleButton : $$anonymous$$onoBehaviour {
private void OnEnable() {
Test.radioToggleEvent += OnToggle;
}
private void OnDisable() {
Test.radioToggleEvent -= OnToggle;
}
public abstract void OnToggle(RadioButton rb, bool b);
}
//this is the actual radio button script to attach each toggle button.
public class RadioButton : ToggleButton {
public bool isToggled;
private void Start() {
isToggled = false;
}
//this method will be triggered for each radio button whenever one of them clicked
public override void OnToggle(RadioButton rb, bool b) {
isToggled = rb.Equals(this); //if toggled button is this one then toggle this button on, else off
//you can do visual arrangements here
}
}