Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class AudioManager : MonoBehaviour {
- public AudioSource musicAudio;
- public AudioClip[] musicClips;
- int currentMusicIndex;
- private void Awake() {
- DontDestroyOnLoad(this);
- }
- void Start() {
- currentMusicIndex = Random.Range(0, musicClips.Length);
- PlayMusic();
- }
- void Update() {
- if (!musicAudio.isPlaying) {
- PlayNextSong();
- }
- }
- #region Music control
- void PlayMusic() {
- // Start playback from the current music index
- musicAudio.clip = musicClips[currentMusicIndex];
- musicAudio.Play();
- }
- void PlayNextSong() {
- // Choose a different track to play
- int newMusicIndex = currentMusicIndex;
- while (newMusicIndex == currentMusicIndex) {
- newMusicIndex = Random.Range(0, musicClips.Length);
- }
- // Set it as the new track and resume playback
- currentMusicIndex = newMusicIndex;
- PlayMusic();
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement