Advertisement
Kisaca121

AudioSource across all Scenes

Jun 12th, 2025
985
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.48 KB | None | 0 0
  1. using System.Diagnostics;
  2. using Unity.PlasticSCM.Editor.WebApi;
  3. using UnityEngine;
  4. using UnityEngine.SceneManagement;
  5.  
  6. public class Music : MonoBehaviour
  7. {
  8.     static Music music;
  9.     [SerializeField] AudioClip menuLoop, gameLoop;
  10.     [SerializeField] AudioSource audioSource;
  11.     string lastScene = "";
  12.     AudioClip newAudioClip = null;
  13.     void Start()
  14.     {
  15.         if (music != null)
  16.         {
  17.             Destroy(gameObject);
  18.         }
  19.         else
  20.         {
  21.             DontDestroyOnLoad(gameObject);
  22.             music = this;
  23.             lastScene = SceneManager.GetActiveScene().name;
  24.             UpdateMusic();
  25.         }
  26.  
  27.         audioSource.Play();
  28.     }
  29.     void Update()
  30.     {
  31.         string currentScene = SceneManager.GetActiveScene().name;
  32.         if (currentScene != lastScene)
  33.         {
  34.             lastScene = currentScene;
  35.             UpdateMusic();
  36.         }
  37.     }
  38.  
  39.     public void UpdateMusic()
  40.     {
  41.         switch (SceneManager.GetActiveScene().name)
  42.         {
  43.             case "Menu":
  44.             case "Settings":
  45.                 newAudioClip = menuLoop;
  46.                 break;
  47.             case "Level 1":
  48.                 newAudioClip = gameLoop;
  49.                 break;
  50.             default:
  51.                 print("No Audio will be playing!");
  52.                 break;
  53.         }
  54.  
  55.         if (newAudioClip != audioSource.clip)
  56.         {
  57.             audioSource.clip = newAudioClip;
  58.             audioSource.Play();
  59.         }
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement