Is there a reason why we cannot use Play and Pause as I have?

// Update is called once per frame
void Update()
{
audioSource.Pause();
ProcessThrust();
ProcessRotation();
}

void ProcessThrust()
{
if(Input.GetKey(KeyCode.W))
{
Debug.Log(“Moving Up”);
rb.AddRelativeForce(Vector3.up * thrustSpeed * Time.deltaTime);
audioSource.Play();
}
}

Does it work the way you want it to work? If so, yeah, sure you can.

Having your “audioSource.play();” in the “if(Input.GetKey(KeyCode.W))” statement would cause the audio clip to be played every frame, its like opening a new music player and hitting play every frame. its going to sound like a bunch of jumble up sound, actually most likely will sound like one bad tone.

the instructor advises to put the “audioSource.Play();” in a if statement checking to see if that audio source is already being played, if true then it wont add another layer of audio clip.

example: (remember that “!” is not)
if (!audioSource.isPlaying)
{
audioSource.Play();
}

Newbie here but you could use the Input.GetKeyDown and -Up commands to combat the audio being started every frame. Code works like a charm:

    void ProcessThrust()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            //Debug.Log("Thrusting");
            rb.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            audioSource.Play();
        } else if (Input.GetKeyUp(KeyCode.Space))
        {
            audioSource.Stop();
        }
    }

I had a similar question, but I did something different.; just 2 steps:

  1. I clicked the checkbox for Loop in the Audio Source in the inspector.
  2. In the thrust method, I set audiosource.enabled = true; Then I added an “else” statement and set to “false” in there when the space bar wasn’t held down.

This seems to run fine; any downside?

Privacy & Terms