Search code examples
c#unity-game-enginedata-storage

Want button click sound to persist from scene to scene


I created an Audiosource from an audio click on all button hits. However, it gets deleted when clicking a button that loads a new scene. I'm wondering if there is an easy way to fix this, like how to add "Dontdestroyonload()" to the audio source somehow.

Code is below:

  private void PlaySound()
    {
        AudioSource.PlayClipAtPoint(buttonClick, Camera.main.transform.position);
        
    }

    public void LoadStartMenu()
    {
        PlaySound();
        SceneManager.LoadScene(0);

    }



Solution

  • U can try like this:

    using UnityEngine;
     
    public class ClassName : MonoBehaviour
    {
      private AudioSource _audioSource;
      private void Awake()
      {
         _audioSource = GetComponent<AudioSource>();
         DontDestroyOnLoad(transform.gameObject);
      }
     
      public void PlaySound()
      {
         if (_audioSource.isPlaying) return;
      _audioSource.PlayClipAtPoint(buttonClick,Camera.main.transform.position);
      }
    }