- Home /
How to make audio not playing repeatedly?
Hi, I made a script that will enable an audio when the button is pressed but then audio start playing like maybe on every frame. here's my script :
void Update() {
if (Input.GetKey("i"))
{
engineOn = true;
}
if (Input.GetKey("o"))
{
engineOn = false;
}
if ((engineOn == true) && (!engine.isPlaying))
{
engine.Play();
}
else
{
engine.Stop();
}
Answer by ninjaguy369 · Jan 30 at 07:34 AM
The top part should be:
if (Input.GetKeyDown("i"))
{
engineOn = true;
}
if (Input.GetKeyDown("o"))
{
engineOn = false;
}
Input.GetKey() will return as true every update that its held down. Input.GetKeyDown() will only be true once when you press the key.
Thanks for your answer. Top line is also one issue (if button was pressed and hold)
but I just realized that the actual issue is in the else {....} line that make the audio sounds broken so I "//" those lines out, Then the audio turns out working fine but I can't stop playing the audio when I pressed "o" now (even though the engineOn is false and other condition that requires engineOn == true stop working.)
Okay, I solve the problem (that audio don't stop working after removing else{...}) by turning off the audio loop.