- Home /
How to play audio clip when destroying an object?
When I try to play an audio clip to signify an object being destroyed I get the error: Can not play a disabled audio source
It seems like when you destroy an object you can't play an associated clip but it's not clear from research on the Internet how to adapt my code. Code shortened to relevant bits.
public class Targets : MonoBehaviour {
//Sound effects
public AudioClip targetDestroyedSound;
public AudioSource gameSounds;
// Start is called before the first frame update
void Start()
{
gameSounds = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
}
private void OnMouseDown()
{
// Function allows users to click on targets and destroy them
if (gameManager.isGameActive)
{
// Destroyed target game sound
gameSounds.PlayOneShot(targetDestroyedSound, 1.0f);
// create particle explosion when clicked on
Instantiate(particleExplosion, transform.position, transform.rotation);
// UpdateScore taken from Game Manager class
gameManager.UpdateScore(pointValue);
// destroys game object if clicked on
Destroy(gameObject);
}
}
private void OnTriggerEnter(Collider other)
{
Destroy(gameObject);
if (!gameObject.CompareTag("Bad"))
{
gameManager.GameOver();
}
}
Answer by dtbrown0801 · Jan 11, 2021 at 07:14 AM
I think the best way to do it would be to have the audio clip on another object (Maybe an AudioManager or just the GameManager) and call a play function for another script or by using a reference.
Answer by melazzeh · Jan 13, 2021 at 12:05 AM
Thanks for this. I did a bit of research and you're right, creating a new GameObject called AudioManager and calling that function from my Target class allows me to play the sound effects when I destroy a target. The only problem is I can play only one sound effect at a time as that is all AudioSource can take! Anyway, back to the grind. Thanks!
Your answer
Follow this Question
Related Questions
Microphone start freezes app 0 Answers
How to stop Audio Track in Timeline? 1 Answer
Need UI Canvas to appear AFTER audio finishes on trigger 2 Answers
Play audio at consistent volume 2 Answers
Recorded Audio empty when used in app 0 Answers