Check a bool method with if statement
How do I check if a function that is given a bool is true?
In this example below the if statement isn't working. I would like to check from void Start() if PlayMusic() is true. What is the proper way to type this?
void Start() {
if (PlayMusic() == true) {
DoSomething;
}
}
public void PlayMusic (bool play) {
if (play) {
DoSomething;
}
} else {
DoSomething;
}
Answer by RealAso · Aug 08, 2017 at 10:24 PM
Try this
public PlayMusic (bool play) {
if (play) {
return true;
}
} else {
return false;
}
by returning a true or false, when using the method it will return true or false depending on the method ALSO NOTE
HAVING 'VOID' IN THE METHOD DEFINITION WILL MAKE IT SO IT WILL NOT RETURN ANYTHING. REMOVE THE 'VOID' (like in the code).
Thank you for your respons.
And is the following code I typed the right way to check the bool? What is the right way to type this, because I get an error on this line:
if (Play$$anonymous$$usic() == true) {
DoSomething;
What is the error that you are getting? I need to know so I can see what's wrong.
Got it working, this is my code. Thanks for helping me out.
// Changing the song when loading a specific level
void ChangeSong() {
if ($$anonymous$$usicState.Get$$anonymous$$usicState () == 1) {
if (lastScene == "$$anonymous$$ain$$anonymous$$enu") {
audioSource.PlayOneShot ($$anonymous$$ain$$anonymous$$enuSongAU, 0.4f);
Debug.Log ("Var lastScene is now: " + lastScene);
} else if (lastScene == "GameStartInfo") {
audioSource.Stop ();
audioSource.PlayOneShot (GreenHillsSongAU, 0.7f);
Debug.Log ("Var lastScene is now: " + lastScene);
} else if (lastScene == "GamePlay1") {
audioSource.Stop ();
audioSource.PlayOneShot (GreenHillsSongAU, 0.7f);
Debug.Log ("Var lastScene is now: " + lastScene);
} else if (lastScene == "GamePlay2") {
audioSource.Stop ();
audioSource.PlayOneShot (CaveSongAU, 0.7f);
Debug.Log ("Var lastScene is now: " + lastScene);
} else if (lastScene == "$$anonymous$$ain$$anonymous$$enuLava") {
audioSource.Stop ();
audioSource.PlayOneShot ($$anonymous$$ain$$anonymous$$enuSongAU, 0.4f);
Debug.Log ("Var lastScene is now: " + lastScene);
}
} else {
audioSource.Stop ();
}
}
public void Play$$anonymous$$usic (bool play) {
if (play) {
if (!audioSource.isPlaying) {
ChangeSong();
}
} else {
if (audioSource.isPlaying) {
}
audioSource.Stop ();
}
}
}
Your answer
Follow this Question
Related Questions
How can I change a function from another script? 1 Answer
How do I call a method with variables in it? 1 Answer
Method Group 1 Answer
List.FindIndex 1 Answer
How can i pass a method like a parameter Unity3d C#? 3 Answers