Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

audio clip to play on collision

Discussion in 'Scripting' started by spazy_t, May 7, 2007.

  1. spazy_t


    Feb 24, 2007
    Im trying to get an audio clip to pay when my character in my game collides with an object.

    At the moment i have the collision calling a static function which is attached to the same game object with the audio clip. However, when calling the static function an error occurs, which tells me that audio.Play(); can not be used as it's not a static member.

    Am i just doing this all wrong, and there is an easier way to do it?

    IO have tried a few other combinations of script in the static function, but keeps creating more errors.

  2. spazy_t


    Feb 24, 2007
    ok, i've had another mess around with it, got it to work via attaching the sound to the character as well as using a script containing PLayOneShot.
  3. redghost


    Mar 7, 2007
    i'm using also playoneshot, straight from the unity script reference

    var click : AudioClip;
    function OnCollisionEnter () {

    but sometimes the sound is playing not only when it collides with other objects, but moving on the terrain as well. How can I fix that?

    edit: I noticed that it happens when the object (sphere) rolls at max speed and sometimes it just makes small bounces on the floor. But it rare happens so it's not big deal I think. :p
  4. cblarsen


    Mar 10, 2007
    @spazy_t: About your first post. A static function belongs to all objects of a class, and not a particular object. Because audio.Play must be called in the context of a paritcular object, the static function has no idea, which object's play function to call.

    I am not quite sure how you solved the problem based on your explanation, but what I would have suggested would be not to make your function static.

    Your object _is_ colliding with the ground all the time. That is what is preventing it from falling forever when gravity is switched on.
    The only reason you are not hearing collision sounds all the time is that in most frames, the object is already colliding, and therefore OnCollisionEnter() does not get called until there has been a single frame where the object did not collide with the ground.

    If you look at the first example here:
    you can see how to only trigger a sound if the collision is hard enough.