- Home /
Calling A Function When A Variable Changes? Help
Hi :)
I am trying to make a script that plays a sound when any of the keys 'W,A,S,D' are held down, and stops it once all the keys a released.
Here's my script so far:
var jetSoundOn : boolean;
function Update ()
{
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))
{
jetSoundOn = true;
audio.Play();
}
else
{
jetSoundOn = false;
audio.Stop();
}
}
The problem is that the sound is being replayed every frame, as its in the Update function. Which makes it sound fricking terrible.
Is there anyway I can make it only call a function (to make it play/stop the sound) when the jetSoundOn variable is changed?
In Lua I think you can use "OnChanged" which would do the job nicely. But I have no idea what to do here :S
Thanks for your help :)
Answer by DavidDebnar · Jul 11, 2013 at 03:38 PM
var jetSoundOn : boolean;
function Update () {
if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D)) {
if(!jetSoundOn) {
jetSoundOn = true;
audio.Play();
}
}
else if(jetSoundOn) {
jetSoundOn = false;
audio.Stop();
}
}
--David--
Worked perfectly, thanks man! Also found out how to use "!" which is a bonus :)
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Inverse function of OnTriggerStay? 3 Answers
Static function and variables error 2 Answers
controlling rigidbody 2d 0 Answers