Creating a Difficulty System toggle switch
2 min readJan 1, 2024
Overview:
In this article we check out how we can make a simple Difficulty System using the toggle switch UI in Unity
Project Set Up:
- Create an empty gameobject, name it ToggleGroup and attach a Toggle Group Component. Make sure to check Allow Switch Off.
2. Create three toggles as children of the ToggleGroup Object.
3. Create and add a script named DifficultySystem to the ToggleGroup Object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DifficultySystem : MonoBehaviour
{
[SerializeField] private List<Toggle> _difficultyToggle = new List<Toggle>();
private void Start()
{
foreach (Transform child in this.gameObject.transform)
{
var toggle = child.gameObject.GetComponent<Toggle>();
_difficultyToggle.Add(toggle);
}
}
public void SelectDifficulty(int difficulty)
{
if (difficulty == 0 && _difficultyToggle[0].isOn)
{
Debug.Log("Difficulty Selected: Easy");
}
else if (difficulty == 1 && _difficultyToggle[1].isOn)
{
Debug.Log("Difficulty Selected: Medium");
}
else if (difficulty == 2 && _difficultyToggle[2].isOn)
{
Debug.Log("Difficulty Selected: Hard");
}
}
}
4. Select each toggle and assign the Difficulty Script and set the appropriate value. 0 for easy, 1 for medium and 3 for hard. Make sure to assign the ToggleGroup to the Group slot.
Now when you select each toggle it should print what you picked.
Thats it for this article.
Thank you for your time and attention.