-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMusicController.cs
More file actions
61 lines (51 loc) · 1.66 KB
/
MusicController.cs
File metadata and controls
61 lines (51 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicController : MonoBehaviour {
/*
Main menu script calls PlayMainMusic
GameManager will call also call PlayMainMusic when it loads, and during
build/play mode changes it will change the music
*/
public AudioClip mainMusic;
public AudioSource audioSource;
// Static singleton instance
private static MusicController instance;
// Static singleton property
public static MusicController Instance
{
// Here we use the ?? operator, to return 'instance' if 'instance' does not equal null
// otherwise we assign instance to a new component and return that
get { return instance ?? (instance = CreateSingleton()); }
}
private static MusicController CreateSingleton()
{
MusicController newInstance;
GameObject newObj = Instantiate(Resources.Load("MusicController")) as GameObject;
newInstance = newObj.GetComponent<MusicController>();
DontDestroyOnLoad(newInstance.gameObject);
return newInstance;
}
void Awake()
{
audioSource = gameObject.GetComponent<AudioSource>();
if (PlayerPrefs.HasKey("MusicVolume"))
{
audioSource.volume = PlayerPrefs.GetFloat("MusicVolume");
}
else
{
PlayerPrefs.SetFloat("MusicVolume", 0.75f);
audioSource.volume = 0.75f;
}
}
public void PlayMainMusic()
{
if (audioSource.clip != mainMusic)
{
audioSource.Stop();
audioSource.clip = mainMusic;
audioSource.Play();
}
}
}