Here are 2 scripts for triggering in-game sound effects:

using UnityEngine;
using System.Collections;

public class ThrowObject : MonoBehaviour {

    public GameObject projectile;
    public AudioClip shootSound;


    private float throwSpeed = 2000f;
    private AudioSource source;
    private float volLowRange = .5f;
    private float volHighRange = 1.0f;


    void Awake () {
    
        source = GetComponent<AudioSource>();

    }


    void Update () {

        if (Input.GetButtonDown("Fire1"))
        {
            float vol = Random.Range (volLowRange, volHighRange);
            source.PlayOneShot(shootSound,vol);
            GameObject throwThis = Instantiate (projectile, transform.position, transform.rotation) as GameObject;
            throwThis.rigidbody.AddRelativeForce (new Vector3(0,0,throwSpeed));
        }
    
    }
}
using UnityEngine;
using System.Collections;

public class CrashSound : MonoBehaviour {

    public AudioClip crashSoft;
    public AudioClip crashHard;


    private AudioSource source;
    private float lowPitchRange = .75F;
    private float highPitchRange = 1.5F;
    private float velToVol = .2F;
    private float velocityClipSplit = 10F;


    void Awake () {
    
        source = GetComponent<AudioSource>();
    }


    void OnCollisionEnter (Collision coll)
    {
        source.pitch = Random.Range (lowPitchRange,highPitchRange);
        float hitVol = coll.relativeVelocity.magnitude * velToVol;
        if (coll.relativeVelocity.magnitude < velocityClipSplit)
            source.PlayOneShot(crashSoft,hitVol);
        else 
            source.PlayOneShot(crashHard,hitVol);
    }

}

 

Tagged on:     

Leave a Reply