Calling A Function When A Variable Changes? Help

Hi :slight_smile:

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 :slight_smile:

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–