Sound still buggy

I believe I got it in how he explained. I still have that glitchy sound when I press on my space bar AND sometimes when I release the key the sound continues. Any ideas from looking at the code?

  private void Rotate()
    {
        if (Input.GetKey(KeyCode.A)) // Turn left
        {
            transform.Rotate(Vector3.forward);
        }
        else if (Input.GetKey(KeyCode.D)) // Turn right
        {
            transform.Rotate(-Vector3.forward);
        }
    }

    private void Thrust()
    {
        if (Input.GetKey(KeyCode.Space)) // You can thrust while rotating.
        {
            rigidBody.AddRelativeForce(Vector3.up); 
                                                    
            if (!audioSource.isPlaying)
            {
                audioSource.Play();
            }
        else
        {
            audioSource.Stop();
        }
        }
    }

Hi Andrew,

The AudioSource starts playing or stops only when Thrust is called. Since it’s constantly called, the first condition is not supposed to be evaluated to true if the space key is NOT pressed.

Add meaningful Debug.Logs to your code blocks to analyse the problem a bit further.

Thank you for the assist. I cleaned up my code a bit and found I missed a curly brace. I had the else statement in the proper spot initially but missed the curly brace and moved it back. This allowed the compiler to work. Then after messing around and staring at it I found the mistake.

if (Input.GetKey(KeyCode.Space)) // You can thrust while rotating.
        {
            print("Space bar pressed");
            rigidBody.AddRelativeForce(Vector3.up * mainThrust); 
            Debug.Log("Sound is not playing. Sound started");
            if (!audioSource.isPlaying)
            {
                audioSource.Play();
            }
        }  // THIS ONE RIGHT HERE
        else
        {
            Debug.Log("Space Bar not pressed. Sound Stopped");
            audioSource.Stop();
        }

I marked the one I had screwed up and fixed. Thank you for making me think a little more.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms