Randomized music
This commit is contained in:
60
Assets/Scripts/GameMusicHandler.cs
Normal file
60
Assets/Scripts/GameMusicHandler.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(AudioSource))]
|
||||
public class GameMusicHandler : MonoBehaviour
|
||||
{
|
||||
public AudioClip[] audioClips;
|
||||
private AudioSource audioSource;
|
||||
private int lastIndex = -1;
|
||||
private bool isPaused = false;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
audioSource = GetComponent<AudioSource>();
|
||||
PlayRandomClip();
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!audioSource.isPlaying && !isPaused) PlayRandomClip();
|
||||
}
|
||||
|
||||
void PlayRandomClip()
|
||||
{
|
||||
if (audioClips.Length == 0) return;
|
||||
|
||||
int index;
|
||||
do
|
||||
{
|
||||
index = Random.Range(0, audioClips.Length);
|
||||
} while (audioClips.Length > 1 && index == lastIndex);
|
||||
|
||||
lastIndex = index;
|
||||
audioSource.clip = audioClips[index];
|
||||
audioSource.Play();
|
||||
}
|
||||
|
||||
public void PauseMusic()
|
||||
{
|
||||
if (audioSource.isPlaying)
|
||||
{
|
||||
audioSource.Pause();
|
||||
isPaused = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void ResumeMusic()
|
||||
{
|
||||
if (isPaused)
|
||||
{
|
||||
audioSource.Play();
|
||||
isPaused = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void RestartMusic()
|
||||
{
|
||||
audioSource.Stop();
|
||||
audioSource.Play();
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/GameMusicHandler.cs.meta
Normal file
2
Assets/Scripts/GameMusicHandler.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 81a98a63df08841c4b3fdc71ceecda4c
|
||||
@@ -639,7 +639,7 @@ public class GamePlayer : MonoBehaviour
|
||||
{
|
||||
Cursor.visible = true;
|
||||
Cursor.lockState = CursorLockMode.None;
|
||||
backgroundMusic.Pause();
|
||||
backgroundMusic.GetComponent<GameMusicHandler>().PauseMusic();
|
||||
pausePanel.SetActive(true);
|
||||
}
|
||||
|
||||
@@ -648,7 +648,7 @@ public class GamePlayer : MonoBehaviour
|
||||
lastMoveTime = Time.time;
|
||||
Cursor.visible = false;
|
||||
Cursor.lockState = CursorLockMode.Locked;
|
||||
backgroundMusic.Play();
|
||||
backgroundMusic.GetComponent<GameMusicHandler>().ResumeMusic();
|
||||
pausePanel.SetActive(false);
|
||||
if (GamePlayerPauseMenu.Instance.editingUI == true) GamePlayerPauseMenu.Instance.ToggleEditingUI();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user