Advertisement
Guest User

Unity AudioManager

a guest
Aug 27th, 2021
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class AudioManager : MonoBehaviour {
  6.  
  7.     public AudioSource musicAudio;
  8.     public AudioClip[] musicClips;
  9.  
  10.     int currentMusicIndex;
  11.  
  12.     private void Awake() {
  13.         DontDestroyOnLoad(this);
  14.     }
  15.  
  16.     void Start() {
  17.         currentMusicIndex = Random.Range(0, musicClips.Length);
  18.  
  19.         PlayMusic();
  20.     }
  21.  
  22.     void Update() {
  23.         if (!musicAudio.isPlaying) {
  24.             PlayNextSong();
  25.         }
  26.     }
  27.  
  28.     #region Music control
  29.  
  30.     void PlayMusic() {
  31.         // Start playback from the current music index
  32.         musicAudio.clip = musicClips[currentMusicIndex];
  33.         musicAudio.Play();
  34.     }
  35.  
  36.     void PlayNextSong() {
  37.         // Choose a different track to play
  38.         int newMusicIndex = currentMusicIndex;
  39.         while (newMusicIndex == currentMusicIndex) {
  40.             newMusicIndex = Random.Range(0, musicClips.Length);
  41.         }
  42.  
  43.         // Set it as the new track and resume playback
  44.         currentMusicIndex = newMusicIndex;
  45.         PlayMusic();
  46.     }
  47.  
  48.     #endregion
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement