PlayClipAtPoint in Unity 5

So for various reasons I am following the course using Unity 5.6.

The problem I have is with the correct Unity 5 c# code for the “crack” sound when the ball hits the bricks.

I have attached an AudioSource to the bricks, if I use the code below the sound will play when it hits a brick and the brick is not destroyed, but not when the brick is destroyed:

GetComponent<AudioSource>().Play();

So this is where in the course it says you should use PlayClipAtPoint, however the below code does not work:

GetComponent<AudioSource>().PlayClipAtPoint();

I know I could put all the audio sounds on the ball, or create a SoundManager, but I just wondered if there was an equivalent to PlayClipAtPoint in Unity 5 so my code can be as close as possible to what is being taught?

Thanks!

1 Like

Hi Joh,

The problem you are having is that you are trying to get a component (AudioSource) of a GameObject that has been destroyed, thus, it doesn’t exist.

The method PlayClipAtPoint is a static method, this means that you do not need an instance of the AudioSource in order to use it, e.g. the one on the brick.

As such, you can just use;

AudioSource.PlayClipAtPoint(clip, position, volume);

You will need to obviously have access to the clip, the position would be the position of the brick typically, the volume is optional and will default to 1.0f if you do not specify it.

This method instantiates a new AudioSource GameObject as needed, and destroys it automatically once the clip has finished playing.

Hope this helps :slight_smile:


See also;

Perfect. Thank you Rob!
Didn’t actually think of trying the code exactly as the course said due to it being different to get it play audio normally! :flushed:

1 Like

You’re very welcome :slight_smile:

Privacy & Terms