Graphics Reference
In-Depth Information
8.1.1 Script Breakdown
This script should be attached to an empty gameObject somewhere in the scene. For the
volume control to work correctly, the gamePrefsName should be set to a name suitable for
describing the game. That way, it will use PlayerPrefs to grab volume levels.
AudioClips should be dragged into the GameSounds array via the Inspector window in
the Unity editor. Each AudioClip in the array will have its own AudioSource and GameObject
instantiated when the BaseSoundController.cs script first runs. Think of each sound as hav-
ing its own audio channel to avoid overlaps or too many different sounds playing on a single
AudioSource. Internally, a class called SoundObject is used to store information about the
audio sources and their gameObjects. When the main sound controller script needs to access
each one, the references in SoundObject are used to avoid having to repeatedly look for them.
The SoundObject class is declared at the top of the 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;
}
The SoundObject single function is to PlaySound(). A position is passed in as a param-
eter, and AudioSource.PlayOneShot() is used to start the AudioClip playback.
PlayOneShot() is a simple method for getting the AudioSource to play the desired
clip without having to set its AudioClip property permanently. To get it to play in the cor-
rect location in the 3D world, the position of the AudioSource is set just before the call to
play it happens:
public void PlaySound(Vector3 atPosition)
{
sourceTR.position= atPosition;
source.PlayOneShot(clip);
}
}
Search WWH ::




Custom Search