Hello. I am at step 59 in https://www.udemy.com/course/unitycourse2/learn/lecture/8336528#overview and I noticed that the Thrust sound continues after dying or transcending even if I have audioSource.Stop() before the PlayOneShot(); (Just keep the space bar pressed as you smash in a wall). Here is my code. Can you spot anything wrong because I can’t.
using UnityEngine;
using UnityEngine.SceneManagement;
public class Rocket : MonoBehaviour
{
[SerializeField] float rcsThrust = 100f;
[SerializeField] float mainThrust = 1000f;
[SerializeField] AudioClip mainEngine;
[SerializeField] AudioClip explosion;
[SerializeField] AudioClip win;
float invokeDelay = 1f;
enum State {Alive, Dying, Transcending};
State state = State.Alive;
Rigidbody rigidBody;
AudioSource audioSource;
// Start is called before the first frame update
void Start()
{
rigidBody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (state == State.Alive) {
RespondToThrustInput();
RespondToRotateInput();
}
}
void OnCollisionEnter(Collision collision)
{
if (state != State.Alive) return;
switch(collision.gameObject.tag)
{
case "Friendly":
print("Friendly");
break;
case "Finish":
HandleCollision(State.Transcending, win, "LoadNextScene");
break;
default:
HandleCollision(State.Dying, explosion, "RestartScene");
break;
}
}
private void HandleCollision(State collisionState, AudioClip sound, string action)
{
state = collisionState;
audioSource.Stop();
audioSource.PlayOneShot(sound);
Invoke(action, invokeDelay);
}
private void RestartScene()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
private void LoadNextScene()
{
if (SceneManager.GetActiveScene().buildIndex == 0)
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
else
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
private void RespondToThrustInput()
{
if (Input.GetKey(KeyCode.Space))
{
ApplyThrust();
}
else
{
audioSource.Stop();
}
}
private void ApplyThrust()
{
float thrustThisFrame = mainThrust * Time.deltaTime;
rigidBody.AddRelativeForce(Vector3.up * thrustThisFrame);
if (!audioSource.isPlaying)
audioSource.PlayOneShot(mainEngine);
}
private void RespondToRotateInput()
{
rigidBody.freezeRotation = true;
float rotationThisFrame = rcsThrust * Time.deltaTime;
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.forward * rotationThisFrame);
}
else if (Input.GetKey(KeyCode.D))
{
transform.Rotate(-Vector3.forward * rotationThisFrame);
}
rigidBody.freezeRotation = false;
}
}