How do I detect what object my ball collided with?

I want to play different sounds when my ball hits walls, paddle and bricks. how do I go about it?

1 Like

Hi Andrey,

In your collision method, you need a bunch of if-statements or a switch. Check the name or the tag of the other game object. Since the method takes in an argument, look that method up in the API and try to figure out more about the object it receives. Via that object, you can get the relevant information about the other game object, e.g. the tag or the name.

And in your if- or case-blocks, you assign the respective sound clip to the AudioSource.

Did this help?

1 Like

Hey Andrey,
this is a fairly common problem and there are many ways to go about solving it.

What I suggest without making it too difficult to comprehend is that you have an array of audio clips of which you assign in the inspector and a reference to your AudioSource.

To show the array in the inspector you can use [SerializeField] attribute or by making the variable public.

You should then use an if or a switch statement when using the callback void “OnCollisionEnter2D(Collision collision)” to check for the tag that the collision information provides.
collision.collider.tag;

and when it collides with the object you want to play a sound on. You can call the reference to your audiosource
e.x. audioSource.PlayOneShot(audioClipArray[0]);

For further improving on it, I suggest looking at Enumerators and how to cast them as integers, floats or strings.

1 Like

thanks

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms