Graphics Reference
In-Depth Information
here are two scripts in this topic related to the playback and management of audio.
One is the sound controller, intended for sound effects, BaseSoundController.cs. The sec-
ond is intended for music control, the script MusicController.cs.
8.1 The Sound Controller
In the example framework for this topic, it is assumed that each scene has a sound con-
troller, an empty gameObject with the BaseSoundController.cs script attached to it. The
component has an array populated in the Unity editor Inspector window by the sounds
required for the game (their AudioClips). When a sound is required by another script, it
calls upon the sound manager to play it, passing in the index of the AudioClip as it stands
in the array:
BaseSoundController.Instance.PlaySoundByIndex( the index number from the
array of sounds );
Centralizing the audio playback avoids dealing with properties in multiple places,
such as having to set the volume level on every AudioSource when a user changes it in the
options menu. When audio is centralized like this, one volume setting and one volume
script can easily change all of the game audio.
Below is the full sound controller script:
using UnityEngine;
using System.Collections;
public class SoundObject
{
public AudioSource source;
public GameObject sourceGO;
public Transform sourceTR;
public AudioClip clip;
public string name;
public SoundObject(AudioClip aClip, string aName, float aVolume)
{
// in this (the constructor) we create a new audio source
// and store the details of the sound itself
sourceGO= new GameObject("AudioSource_"+aName);
sourceTR= sourceGO.transform;
source= sourceGO.AddComponent<AudioSource>();
source.name= "AudioSource_"+aName;
source.playOnAwake= false;
source.clip= aClip;
source.volume= aVolume;
clip= aClip;
name= aName;
}
public void PlaySound(Vector3 atPosition)
{
sourceTR.position= atPosition;
source.PlayOneShot(clip);
}
Search WWH ::




Custom Search