Search Unity

Help with engine sound effects?

Discussion in 'Scripting' started by TonyNowak, Jul 31, 2017.

  1. TonyNowak

    TonyNowak

    Joined:
    May 10, 2010
    Posts:
    316
    My audio source originally was set to play on awake and loop and played a generic engine sound, now I want to expand that functionality, so I made 3 sounds, engine idle, reverse, accelerate, and since the AudioSource is already always playing, I just thought I could switch the clips around. Well, now it doesn't work, and the clips don't change in the AudioSource even though the code tells them, adding the Play bit (which i commented out) makes them all play at once? How can I fix this and make it so the sounds play correctly, for accelerate, reverse, and idle (looping of course). Here is my code:

    https://hastebin.com/egoxogeqar.cs
     
  2. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    Instead of just setting the clip, you should call Stop(), set clip, call Play();
     
  3. TonyNowak

    TonyNowak

    Joined:
    May 10, 2010
    Posts:
    316
    Last edited: Jul 31, 2017
  4. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    The problem is that these calls (Input.GetButton("xxx")) will return true "while" the button is down. That means every update loop which the button is down, you'll be stopping, changing and starting the music again.

    Two options, either track which is playing only act if needed. or use Input.GetButtonDown("xxx") instead, as this will only be true in the frame that the button is pressed down in (and not when it's being held down).