Krebsey
Krebsey

Reputation: 29

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);

    }


Upvotes: 1

Views: 136

Answers (1)

Celal Alisoy
Celal Alisoy

Reputation: 51

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);
  }
}

Upvotes: 1

Related Questions