How to Play a Sound Effect When Enemy is Destroyed

I’ve been putting together a simple game, and I want to play a sound effect for when an enemy is destroyed. The enemy, which is a prefab (not sure if that affects anything), is destroyed when the player clicks on it. At the moment, the sound effect is played when the enemy prefab is generated, not when it is destroyed. I’m very new at this, so if anyone is willing to help out, I would greatly appreciate any assistance. Thanks in advance.

using UnityEngine;
using System.Collections;

public class EnemyDestroy : MonoBehaviour {
	public int scoreValue = 1;
	public AudioClip theSound;
	AudioSource soundClip;

	void Start(){
		soundClip = GetComponent<AudioSource> ();
		soundClip.playOnAwake = false;
	}

	// Use this for initialization
	void OnMouseDown(){
		if (gameObject.tag == "Enemy") {
			ScoreManager.score += scoreValue;
			soundClip.PlayOneShot (theSound, 0.8f);
			Destroy (gameObject);
		}
	}
}

I should have seen this earlier... There's a pair of braces missing. if (Input.GetButton("Fire1") && Time.time > NextFire) { NextFire = Time.time + FireRate; Instantiate(Shot, ShotSpawn.position, ShotSpawn.rotation); }

2 Answers

2

I am new to Unity and i am not that good at script, but you could make a play sound on collider.

You said the enemy is destroyed AFTER you click on it, right? It’s just one time? Because if it is, you can make what i said. It’s pretty simple, here’s a tutorial.

/\ | The tutorial above teach you how to trigger an audio when the colider of a object is hit. I am pretty sure it will work.

Well, even though that tutorial is in JavaScript, I still believe that follow the format of the example and it still doesn’t work. Also, the tutorial is from four years ago, so things may have changed since then. I appreciate the suggestion, but if you have any other thoughts, I wouldn’t mind hearing them.

FOR FOX CREEK!!!!....LOL thanks for that just tried it and all good thanks for your help on that not sure how I missed that but sometimes another set of eyes helps Cheers!