Extra sound effect not working

On my own I am trying to add an extra sound i downloaded from internet for when im not pressing space with the rocket. AudioClip is called “rotating” for this special new sound im trying to implement. Here is the code:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Movement : MonoBehaviour

{

[SerializeField] float thrustSpeed = 100;

[SerializeField] float rotationSpeed = 5;

[SerializeField] AudioClip mainEngine;

[SerializeField] AudioClip rotating;

Rigidbody rb;

AudioSource audioSource;

// Start is called before the first frame update

void Start()

{

    rb = GetComponent<Rigidbody>();

    audioSource = GetComponent<AudioSource>();

}

// Update is called once per frame

 void Update()

{

    AddThrust();

    AddRotation();

}

void AddThrust()

{

    if(Input.GetKey(KeyCode.Space))

    {

       

        rb.AddRelativeForce(Vector3.up * thrustSpeed * Time.deltaTime);

        if (!audioSource.isPlaying)

        {

        audioSource.PlayOneShot(mainEngine);

        }

       

    }    

    else

    {

         audioSource.Stop();

         if (!audioSource.isPlaying)

        {

        audioSource.PlayOneShot(rotating);

        }

                                    

    }  

}



void AddRotation()

{

if(Input.GetKey(KeyCode.A))

    {

        ApplyRotation(rotationSpeed);

    }

    else if(Input.GetKey(KeyCode.D))

     {

        ApplyRotation(-rotationSpeed);

     }

}

void ApplyRotation(float rotationThisFrame)

{

    rb.freezeRotation = true; // freezing rotation to manually rotate

    transform.Rotate(Vector3.forward * rotationThisFrame * Time.deltaTime);

    rb.freezeRotation = false;

}

}
I think the key to this code lies between these lines:

if (!audioSource.isPlaying)

        {

        audioSource.PlayOneShot(rotating);

        }

but still I cant manage to play my extra sound. Can someone let me know what is the correct code to implement this extra sound?

I think you keep stopping it so it never gets a chance to play.

Let’s make a simple method to help with this. Put this in your Movement script and it should help you out

void AddThrust()
{
    if(Input.GetKey(KeyCode.Space))
    {
       
        rb.AddRelativeForce(Vector3.up * thrustSpeed * Time.deltaTime);
        // Play the main engine sound
        PlayClip(mainEngine);
    }    
    else
    {
        // Play the rotating sound
        PlayClip(rotating);
    }
}

void PlayClip(AudioClip clip)
{
    // If we're already playing this clip, just return
    if (audioSource.isPlaying && audioSource.clip == clip) return;

    // Stop the current clip
    audioSource.Stop();

    // Set the new clip, and play it
    audioSource.clip = clip;
    audioSource.Play();
}
1 Like

thanks that works! thank you for your time

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

Privacy & Terms