A minor question about proposed solution

Hi Ben!

I have a question about your proposed solution. Isn’t the problem still there - just that, perhaps, there’s nanosecond or microsecond difference to putting the code in Awake() instead of Start()?

Isn’t the problem actually got to do with “Play on awake”

As long as that is checked, the audio starts off playing. So to give a test, here’s something to run. The output I get is that the newly created MusicPlayer is already playing.

void Awake ()
{
	AudioSource audio = GetComponent<AudioSource> ();
	if (!audio.isPlaying) {
		Debug.Log ("Music not playing");
	} else {
		Debug.Log ("Music is playing");
	}

	if (instance != null) {
		Destroy (gameObject);
		Debug.Log ("Duplicate music player self-destructing!");
	} else {
		instance = this;
		GameObject.DontDestroyOnLoad (gameObject);
	}
}

To fix that, shouldn’t “Play on awake” be disabled first.
Then, change the code to something like this:

void Awake ()
{
	AudioSource audio = GetComponent<AudioSource> ();
	if (!audio.isPlaying) {
		Debug.Log ("Music not playing");
	} else {
		Debug.Log ("Music is playing");
	}

	if (instance != null) {
		Destroy (gameObject);
		Debug.Log ("Duplicate music player self-destructing!");
	} else {
		instance = this;
		GameObject.DontDestroyOnLoad (gameObject);

		if (!audio.isPlaying) {
			Debug.Log ("Begin playing music");
			audio.Play ();
		}
	}
}

Of course, after removing all debug messages, I’d instantiate AudioSource after GameObject.DontDestroyOnLoad (gameObject) instead.

Cheers!
~ Daniel

Privacy & Terms