Audio play when object hit collision.

Hi :slight_smile: How can i make audio play when object hit collision,just like in portal 2 game when cube hits the ground or other collisions it plays “impact” sound,guys i need script example cause i dont understand ANYTHING about this,so please help me :)) thanks for attention.

P.S. Its more like physics sound or something…

Just like in bootcamp demo game,when barrels and other stuff falling down it plays "impact" sound

Can anyone help me?

2 Answers

2

You can look on the script reference for a nice example of how something that can work for you here:Unity - Scripting API: AudioSource.PlayOneShot

Here is something else that work, but it requires you to have a collider on your objects that makes them triggers.

AudioClip impact;

void OnTriggerEnter (Collider other) 
	{
	 if(other.gameObject.tag == "Floor")
		{
			Audio.PlayOneShot(impact);
		}
			
	}

Here’s an example. Note: Untested code!

Where the sound comes from the cube, attach the AudioSource component to the cube and put in the sound effect. Add a collider to both the cube and the floor and select. Add this script to the cube.

 function OnTriggerEnter(hit : Collider) {
      if(hit.name == "floor" || hit.gameObject.tag == "floor")
           audio.Play();
 }

Where the sound comes from the floor, attach the AudioSource component to the floor and put in the sound effect. Add a collider to both the cube and the floor. Add this script to the floor.

 function OnTriggerEnter(hit : Collider) {
      if(hit.name == "cube" || hit.gameObject.tag == "cube")
           audio.Play();
 }

You may or may not need to select IsTrigger in your colliders depending on what you want to occur when the cube hits the ground.