I have this code for setting up game difficulty:
public void SetEasyDifficulty ()
{
gameState.difficulty = Helper.EASY_DIFFICULTY;
//easyDifficultyToggle.isOn = true;
mediumDifficultyToggle.isOn = false;
hardDifficultyToggle.isOn = false;
gameState.Save();
}
public void SetMediumDifficulty ()
{
gameState.difficulty = Helper.MEDIUM_DIFFICULTY;
easyDifficultyToggle.isOn = false;
//mediumDifficultyToggle.isOn = true;
hardDifficultyToggle.isOn = false;
gameState.Save();
}
public void SetHardDifficulty ()
{
gameState.difficulty = Helper.HARD_DIFFICULTY;
easyDifficultyToggle.isOn = false;
mediumDifficultyToggle.isOn = false;
//hardDifficultyToggle.isOn = true;
gameState.Save();
}
The reason why specific lines are commented is because when uncommented and I press one of the toggles, Unity gets stuck and I have to kill the process in task manager.
On the other hand, if those lines stay commented, all works except I need to press twice, the same toggle to enable it
What could be the problem here?
How did I solved this? There is a ToggleGroup component which can be added to an empty GameObject. So create an empty game object and press the “add component” to add UI → Toggle Group. Once you have done that select each of your toggles and fill the Toggle Group field with this empty object. This will set up all toggles in one group and once done that, you can use the following code to find which toggle is currently enabled:
using UnityEngine;
public MyToggleClass:MonoBehaviour
{
public GameObject toggleGroupHolder;
ToggleGroup tGroup;
IEnumerator<Toggle> gameDiffEnum;
string toggleName = "";
public void SetGameDifficulty ()
{
gameDiffEnum = tGroup.ActiveToggles().GetEnumerator();
gameDiffEnum.MoveNext();
toggleName = gameDiffEnum.Current.name;
if (toggleName == Helper.EASY_DIFFICULTY_TOGGLE)
{
gameState.difficulty = Helper.EASY_DIFFICULTY;
}
if (toggleName == Helper.MEDIUM_DIFFICULTY_TOGGLE)
{
gameState.difficulty = Helper.MEDIUM_DIFFICULTY;
}
if (toggleName == Helper.HARD_DIFFICULTY_TOGGLE)
{
gameState.difficulty = Helper.HARD_DIFFICULTY;
}
gameState.Save();
}
}
Make sure to fill toggleGroupHolder with the empty object we created and set onValueChanged() event handler for each of the toggles to SetGameDifficulty(). SetGameDifficulty() will be called twice