I have a problem playing an AudioSource
I'm trying to make a bullet play a sound when it hits a wall. The bullet currently has 2 AudioSources - one which plays immediately after a bullet is spawned (this one works) and another one called "Impact" which is supposed to play when I hit a wall. The problem is that I don't know how to properly write the script to make it play that sound.
This is the bits of code that I have:
public class BulletController : MonoBehaviour
{
//some more variables
private AudioSource ImpactAudio;
// Use this for initialization
[UsedImplicitly]
private void Start()
{
//some extra things for the player
//I debugged this and it does assign the correct AudioSource
//to ImpactAudio
ImpactAudio = GetComponents<AudioSource>()[1];
}
[UsedImplicitly]
private void OnTriggerEnter2D(Collider2D otherCollider)
{
switch (otherCollider.name)
{
//some other cases
case "Block":
PlaySound();
//This part works - the bullets are actually destroyed by this
Destroy(gameObject);
BitBoy.ReloadBullet();
break;
default:
Debug.Log(otherCollider.name);
break;
}
}
//This should(?) play the Impact sound
private void PlaySound()
{
//This does write Impact in the console
Debug.Log("Impact");
//Nothing happens.
ImpactAudio.Play();
}
}
I am pretty new to Unity, just started working, but after searching through some previous questions related to this I still don't have a solution.
Answer by OctoMan · Dec 20, 2015 at 01:30 AM
ImpactAudio = GetComponents<AudioSource>()[1];
shouldn't it be ?
ImpactAudio = GetComponents<AudioSource>();
No, the former is picking the second audio source on the game object, the latter is picking ALL of the audio sources on the game object.
Why would you use more than 1 audio source?
Anyways, did you added a audio clip into your audio source?
Answer by Statement · Dec 20, 2015 at 01:40 AM
PlaySound();
Destroy(gameObject);
It appear that the problem is that you destroy the game object that is meant to play the sound. You can't destroy the object and expect the same object to do stuff after it has been destroyed.
To solve your problem, tell another game object to play the sound at its location.
Sounds right, or add some delete time:
Destroy(gameObject, 1f);
But that doesn't make much sense unless you also remove colliders/graphics/other scripts from the game object. It'd be silly to have an object linger around only so the audio source can continue playing.
Your answer
Follow this Question
Related Questions
C# Setting AudioMixerGroup through code 2 Answers
Audio help 0 Answers
Second AudioClip won't play 0 Answers
How do I get the parent from a AudioMixerGroup Object 2 Answers
Second AudioClip won't play 0 Answers