- Home /
Audio play when object hit collision.
Hi :) 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
Answer by Msurdej · Dec 09, 2012 at 08:45 PM
You can look on the script reference for a nice example of how something that can work for you here:http://docs.unity3d.com/Documentation/ScriptReference/AudioSource.PlayOneShot.html
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);
}
}
Answer by cassius · Dec 11, 2012 at 05:49 PM
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.