Using static string for singleton instead of static instance

In trying to make sure I understood the concept of singletons, I created a way to do it with a string, "on and “off”. Was wondering why you shouldn’t do this? It works, but I’m wondering if it will create problems down the line.

using UnityEngine;
using System.Collections;

public class MusicPlayer : MonoBehaviour {

	static string music_switch = "off";

	void Awake () {
		if (music_switch == "on"){
			Destroy(gameObject);
		}
		else {
			music_switch = "on";
			DontDestroyOnLoad(gameObject);
		}
	}
}
using UnityEngine;
using System.Collections;

public class MusicPlayer : MonoBehaviour {


	static string music_switch = "off";

	void Awake () {
		if (music_switch == "off"){
			music_switch = "on";
			DontDestroyOnLoad(gameObject);
		}
		else if(music_switch == "on"){
			Destroy(gameObject);
		}
	}
}

I actually like this better, has a better flow.

Hmmm I read the first one, and think it makes sense to me… But the second one seems less intuitive to me. Thanks for sharing!

The second one, I just like it from the concept of a light switch. If the light is off, turn it on and don’t destroy that instance. Every instance that comes after, the switch is already on, so destroy them.

Privacy & Terms