Time for action – adding background music
Let's get started with a single script to control our background music.
- We will start by creating a new script and naming it
FadeIn
. - This script begins with three variables. The first is the goal volume that the script has to reach. The second is the number of seconds the transition will take. The last is the time when the transition began.
public float maxVolume = 1f; public float fadeLength = 1f; private float fadeStartTime = -1f;
- Next, we make use of the
Awake
function. It begins by looking at theaudio
variable, which is automatically supplied by Unity, to check for an attached Audio Source component. If one cannot be found, thegameObject
is destroyed and the function is exited.public void Awake() { if(audio == null) { Destroy(gameObject); return; }
- The
Awake
function ends by setting its volume to0
and playing it if it isn't already.audio.volume = 0; if(!audio.isPlaying) audio.Play(); }
- To cause the transition...