0
\$\begingroup\$

I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so.

How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played?

This is my "LevelMaster" script which is responsible for handling the audio in each scene.

public class LevelMaster : MonoBehaviour
{
private AudioManager AudioManager;

[SerializeField]
private string trackName;

private void Start()
{
    AudioManager = GameObject.Find("AudioManager").GetComponent<AudioManager>();
    AudioManager.Play(trackName);
}

public void PlaySound(string soundName)
{
    AudioManager.Play(soundName);
}

public void StopSound(string soundName)
{
    AudioManager.Stop(soundName);
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Since you're passing a string on AudioManager.Play(), I assume you're using a Dictionary < string, AudioSource > on your AudioManager.

You could change the Start code to the following:

private void Start()
{
    AudioManager = GameObject.Find("AudioManager").GetComponent<AudioManager>();
    if (!AudioManager.dictionary[trackName].isPlaying)
        AudioManager.Play(trackName);
}

Or, you could store a reference to the AudioSource used when you call AudioManager.Play(). This way you'll always have a reference to the last AudioSource played.

\$\endgroup\$
1
  • \$\begingroup\$ Ah, I didn’t think to use isPlaying, it seems so obvious now. Thank you! \$\endgroup\$ Commented May 8, 2018 at 8:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .