- Home /
If not working as expected.
I am rather new to coding and I have tried to search for a solution to this problem but I can not find it.
I have a script sending a raycast so that whenever I press the 'E' key it sends the message "use" from that script to this script. This seems to be working as I need it to, however the If-else statement in this script is not doing what I need it to do.
#pragma strict
var toggledOn : boolean = false;
var onSound : AudioClip;
var offSound : AudioClip;
var toggleSound : AudioSource;
function Start(){
var aSources = GetComponents(AudioSource);
toggleSound = aSources[1];
}
function use(){
if (toggledOn == true){
toggledOn = false;
audio.PlayOneShot(offSound);
}
else {
toggledOn = true;
audio.PlayOneShot(onSound);
toggleSound.Play();
}
}
To my understanding (that is obviously flawed), whenever the other script sends the message "use" to this script, it should be then running the if statement, and if the requirement is not met, then the else statement should run. However, when I press "E" all that happens is it runs the audio.PlayOneShot(onSound); toggleSound.Play(); part. It does not appear to be setting the toggledOn variable to true; it only plays the two sounds.
If I set the variable toggledOn to true before running the game, it continues to do the same thing. (It doesn't seem to matter whether or not the variable is set to true or false, each yields the same result.)
Are you sure offsound and onsound are different sounds?
Yes. Also, the way I understand that this script should work, is that it would change the variable toggledOn to true/false every time I press "e", which it is not doing either.
When checking Input for the keypress "E", do you happen to be using Input.Get$$anonymous$$ey ins$$anonymous$$d of Input.Get$$anonymous$$eyDown? That could cause the "use" function to fire on multiple consecutive frames
Is there any other script or code snippet that sets the toggledOn variable? Some other script could be changing it to false.
Answer by aldonaletto · Jul 31, 2013 at 01:40 PM
This code should work, although there's an easier way to toggle a boolean variable. You could add debug lines to your code, like this (boolean toggled in a different manner):
function use(){
toggledOn = !toggledOn; // toggle the boolean
Debug.Log("use called - toggledOn now is "+toggledOn);
if (toggledOn){ // toggledOn became true
audio.PlayOneShot(onSound);
toggleSound.Play();
} else { // toggledOn became false
audio.PlayOneShot(offSound);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613111250im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
if statement for 6 ints help C# 2 Answers
If statement always true 3 Answers
Any Ideas on how to solve this? 1 Answer
Need Help Improving If Else statement 1 Answer
Prevention of air movement 1 Answer