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. Wh
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.
I guess the two functions isMale and isFemale are Toggles' event handlers. According to Unity docs:
The Toggle has a single event called On Value Changed that responds when the user changes the current value
So the problem is that these event handlers respond to value change and not toggle being checked, so your code causes an infinite loop. It should work by reading them first to make sure it's a check and not uncheck:
public void isMale(){
if (!male.isOn) return;
if (female.isOn)
female.isOn = false;
male.isOn = true;
}
public void isFemale(){
if (!female.isOn) return;
if (male.isOn)
male.isOn = false;
female.isOn = true;
}