Sound Effects & Scripting

確認済のバージョン: 4.5

-

難易度: 初級

In this training session we demonstrate how to add sound effects to your game that are triggered by game events, using C# scripting. We also review the main audio components of Unity: Audio Listeners, Audio Sources and Audio Clips. Tutor - Matt Schell

Sound Effects & Scripting

初級 Audio

This script instantiates a projectile prefab and plays a sound with randomized volume.

ThrowObject

Code snippet

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));
        }
    
    }
}

CrashSound

Code snippet

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);
    }

}

関連するチュートリアル