Delay on Death and multiple soundeffects

Greetings,

I’m trying to make a menu Delay upon death using a Coroutine. But i can’t seem to get it to work and i don’t know why, i’ve used some different methods from other posts but still can’t seem to fix it. Also i’m trying to trigger a sound effect for when the tank explodes! But it doesn’t even fire up. The other sound effect (audio.PlayOneShot(TankHit); ) has no problem tho.

I hope some of you could explain to me what i am doing wrong here.

Thanks in advance, And here is the Tank controller class

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class Tank1Controller : MonoBehaviour {

  private Rigidbody2D rb2d;
  public float Speed;
  public int Health = 5;

  private Vector2 moveInput;
  private Vector2 moveVelocity;

  public int score1;
  public Tank2Controller tk2;

  public GameObject AnimExplosion;

  public AudioClip TankHit;
  public AudioClip TankExplosie;
  new AudioSource audio;

  public float delayTime = 3;

     void OnGUI()
  {
  GUI.color = Color.red;
  GUI.Label(new Rect(5, 10, 130, 40), "Player 1 Health: " + Health.ToString());
  GUI.Label(new Rect(5, 40, 130, 40), "Player 1 score: " + score1.ToString());
  }

     void Start()
  {
  rb2d = GetComponent<Rigidbody2D>();
  audio = GetComponent<AudioSource>();
  }

  void Update()
  {

     if (Health == 0)
  {

  audio.PlayOneShot(TankExplosie);
  Instantiate(AnimExplosion, transform.position, transform.rotation);
   
  tk2.score2++;

  StartCoroutine(WaitForSceneLoad());
  Destroy(gameObject);
  }
  

     if (Input.GetKey(KeyCode.W))
  {
  transform.Translate(0, Speed * Time.deltaTime, 0);
  }
  if (Input.GetKey(KeyCode.S))
  {
  transform.Translate(0, -Speed * Time.deltaTime, 0);
  }
  if (Input.GetKey(KeyCode.D))
  {
  transform.Rotate(Vector3.back, Time.deltaTime * 180, Space.Self);
  }
  if (Input.GetKey(KeyCode.A))
  {
  transform.Rotate(Vector3.forward, Time.deltaTime * 180, Space.Self);
  }
  }

     void OnCollisionEnter2D(Collision2D collision)
  {
  if (collision.gameObject.name == "Projectile(Clone)")
  {
  Health = Health - 1;
  audio.PlayOneShot(TankHit);
  }
  }

     private IEnumerator WaitForSceneLoad()
  {
  yield return new WaitForSeconds(2);
  SceneManager.LoadScene("Menu");

  }
}

Well, you do use a Destroy(gameObject), which will destroy the Game Object that has this script on it. Anything associated with the Game Object will be destroyed as well. Which includes; the sound you are trying to play and the coroutine.

1 Like