Playing and stopping rocket audio

Hi community,
I’m in the learning process and have a little bug which I can’t fix.
When I play the game and press the space bar, the sound plays not one time and it repeats and repeats and you hear a distorted sound. I checked my code but couldn’t find out why.
Here is the code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rocket : MonoBehaviour {

    Rigidbody rigidBody;
    AudioSource audioSource;


    void Start () {
        rigidBody = GetComponent<Rigidbody>();
        audioSource = GetComponent<AudioSource>();

	}
	
	// Update is called once per frame
	void Update ()
    {
        Thrust();
        Rotate();

	}

    private void Thrust()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            rigidBody.AddRelativeForce(Vector3.up);
            print("Thrusting");

            //so it doesn't layer the sound on each other
            if (!audioSource.isPlaying)
            {
                audioSource.Play();
            }
            else
            {
                audioSource.Stop();
            }

        }
    }
    private void Rotate()
    {
        rigidBody.freezeRotation = true; //make manual control of rotation

        if (Input.GetKey(KeyCode.A))
        {
            transform.Rotate(Vector3.forward);
            print("Rotating Left");
        }
        else if (Input.GetKey(KeyCode.D))
        {
            transform.Rotate(-Vector3.forward);
            print("Rotating Right");
        }
        rigidBody.freezeRotation = false; // resume physics control of rotation
    }
}

Hi,

Have a look at the AudioSource component on the Rocket and see if it has Loop ticked;

image

Also, please apply code formatting when copy/pasting your code, it makes it a lot easier to read, link below to help :slight_smile:


See also;

Hi Rob and thank you very much for your swift reply.
I found the error on my code. My else statement was placed inside the if statement for playing the sound. This is the corrected version of Thrust():

 private void Thrust()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            rigidBody.AddRelativeForce(Vector3.up);
            print("Thrusting");

            //so it doesn't layer the sound on each other
            if (!audioSource.isPlaying)
            {
                audioSource.Play();
            }
        }
        else
        {
            audioSource.Stop();
        }

        
    }
1 Like

Aha! Well done, good catch! I missed that in your above example, sorry (I was busy applying your code formatting! :wink: )

1 Like

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

Privacy & Terms