- Home /
The question is answered, right answer was accepted
Unity 4.6 Checkbox! How does it work?
Hi!I want to use a checkbox for my game's options menu.I am not sure how the new checkbox works.How can I set a function for when it is checked and when it is not? What I am trying to do is a checkbox that disables and enables sound. Please help! Ty
Answer by HarshadK · Dec 03, 2014 at 02:11 PM
You can write a function that will be called on value changed for the toggle. Just write this function and add under the Toggle (Script) component there is an option for On Value Changed. Click the plus button and then drag and drop the game object with the script containing for this function. Then select the function from the list. (This is the same as On Click for a button)
Remember that this function have to be public and has a return type of void.
You can check the state of toggle using isOn variable of that toggle.
The script will be:
using UnityEngine.UI;
public class ChangeVolume : Monobehaviour {
[SerializeField]
Toggle musicToggle; //Drag and drop your toggle game object here or you can even get a reference to this in Start()
public void SetMusic()
{
if(musicToggle.isOn) {
// Set music On
} else {
// Set music Off
}
}
}
You can also declare public void Set$$anonymous$$usic (Toggle musicToggle)
and pass the toggle in that way by attaching itself to this field in the Toggle inspector.