[TIP] How to make your Sound plays only when hits the paddle

Hello everyone, I was scratching my head for some time… “why I have to hear my “boing” sound on every brick, I want it only for my paddle!!!”.

So I tried some things, I knew it has something to do with tags BUT… [FAILED]
Search on the forum. [Didn’t find anything]
So… Google is our friend.

So I’ll post my way here, if someone else wants to have more than 1 sound for his/her buncing ball. :slight_smile:

First you need to put a tag on your paddle! (Ben told us how to change tags!)


And then the code I changed inside ball.cs

> void OnCollisionEnter2D (Collision2D collision){
> 		if (hasStarted){
> 			if (collision.gameObject.tag == "Paddle"){
> 				GetComponent<AudioSource>().Play();
> 			}
> 		}
> 	}

Hope that will help you have a better sleep and a better BlockBreaker!

1 Like

Hi JohnB. I also noticed that the “boing” sound was playing on every collision the ball made. So I set out to right this. In the OnCollisionEnter2D method in Ball.cs, I began to look at the properties of the passed in collision. I noticed that collision.gameObject returns the colliding object. So with that in mind, I put an if block to see if the ball is colliding with the paddle object:

        if(collision.gameObject.ToString() == paddle.gameObject.ToString())

This method works without needing to set a tag.


Hey guys, I’m brand new and have been trying to figure out how to make the audio only play when it hits the paddle.

Weezle1, I used your solution but I couldn’t figure out the purpose of adding ToString() in the if statement.

I ended up doing it like this and it seems to work fine. Is this going to give me issues at some point?

void OnCollisionEnter2D(Collision2D collision)
    if (hasStarted)
        if (collision.gameObject == paddle.gameObject)

Anyone’s input would be appreciated.

1 Like

The ToString method call isn’t necessary.

Also, I wouldn’t keep using GetComponent calls in each collision. If you know there are going to be multiple collisions, which we do (unless the player is utterly useless I suppose), we can assume that the paddle will have the need for this component reference multiple times, so, to slightly improve performance, use a private variable to store a reference to the AudioSource and populate it once within the Awake method. Then use the private variable within the OnCollisionEnter2D method to play the clip.

So, @Paul_Mac, if your variable audio is private and populated in this way, I’d say you’re spot on. :slight_smile:

1 Like

Great, thanks for your help!

1 Like

Privacy & Terms