Another Method of Scripting. A little bit simplier

using UnityEngine;
using System.Collections;

public class MusicPlayer : MonoBehaviour {

	public static int musicCounter = 0;

	// Use this for initialization
	void Start () {
		GameObject.DontDestroyOnLoad(gameObject);
		musicCounter++;
		if(musicCounter > 1){
			GameObject.DestroyObject(gameObject);
		
		}
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
1 Like

Also I did this that gets the work done if you uncheck the “play on awake” on music source component. but your code think is better
This 2 maybe takes less CPU usage. :slight_smile:

public class MusicPlayer : MonoBehaviour
{

    public static bool musicLoaded = false;

    private void Start()
    {
        if (musicLoaded == false)
        {
            this.GetComponent<AudioSource>().Play();
            GameObject.DontDestroyOnLoad(gameObject);
            musicLoaded = true;
        }
    }
}

Also, stated in another discussion on this topic, you could overload the int if you played over the amount that the int type could hold. A classic example of this bug is the overly aggressive Ghandi on of the earlier Civilization games. It’s the ‘integer overload’ problem. Best to use a Boolean as @Petros_Petrakis has stated.

Privacy & Terms