M.Waqas Pervez M.Waqas Pervez - 1 month ago 20
C# Question

Unity 5 unresponsive after a piece of code is executed

I am a absolute beginner in unity. I have been working on an UI which is a simple login form. In which I have two

Toggle
for selecting gender i.e male or female. What I have been doing is that calling a method which checks if a male is already selected it will remove the check from male when the other toggle is pressed.

My
Unity
freezes when I click the female
Toogle
. here is my code.

Toggle female;
Toggle male;
void Start(){
female = GameObject.Find ("toggle_female").GetComponent<Toggle> ();
male = GameObject.Find ("toggle_male").GetComponent<Toggle> ();
}

public void isMale(){
if (female.isOn)
female.isOn = false;

male.isOn = true;

}

public void isFemale(){
if (male.isOn)
male.isOn = false;

female.isOn = true;
}

Answer

You are running into infinite loop with your Toggle.

When the female toggle changes, the onValueChanged event is triggered. I assume that your isFemale() function is linked with the Toggle onValueChanged event, so isFemale() will be called.

When isFemale() is called, it will do male.isOn = false; causing isMale() function to be called which will then run female.isOn = false; causing isFemale() to be called again. This is everlasting.

The onValueChanged event should never be fired when isOn is set from script. This is the problem.

Solution:

You are looking for the ToggleGroup.

1.Create male toggle GameObject -> UI -> Toggle then name it Male toggle.

2.Create female toggle GameObject -> UI -> Toggle then name it Female toggle. You can change the label text later on.

3.Create an empty GameObject. GameObject -> Create Empty. Rename it to ToggleGroup.

Select the newly created GameObject, go to Component -> ToggleGroup. Now, you have GameObject called ToggleGroup with ToggleGroup Component attached to it.

4.Select your Male toggle, then drag the ToggleGroup GameObject into Male toggle's Group slot. Select your Female toggle, then drag the ToggleGroup GameObject into Female toggle's Group slot

Select your Female toggle, then unckeck Is On checkbox to make sure that only one(Male toggle) is selected by default. Click play and now, only one toggle can be selected at a time.

enter image description here

Comments