Sign In Register

How can we help you today?

Start a new topic

GameSparks GameObject Singleton (Unity)


The GameSparksUnity.cs script marks the object in which it's attached as DontDestroyOnLoad. Suppose you have a first scene in your game where you create this object (e.g. your main menu). Every other scene will have access to this game object. But, what if you're developing another scene, which you want to test independently while you develop without changing to your initial scene before running the game. You need to add another GameSparksUnity object to your hierarchy... now, what happens when you test your game running from that initial scene, and eventually reach the scene you were developing where you created another GameSparksUnity object? You will now have 2 instances. What if this scene is something that you can access many times? You will have many don't-destroyed-on-load instances of this object.


Add this code to GameSparksUnity.cs to make it singleton, thus preventing multiple instances:


private static GameSparksUnity instance;
public static GameSparksUnity Instance {
	get{ return instance; }

private static object singletonLock = new object();

private void Awake() {
	lock(singletonLock) {
		GameSparksUnity[] instances = GameObject.FindObjectsOfType<GameSparksUnity>();
		if(instances != null && instances.Length > 1 && instance != this) {
			Debug.Log("Destroying duplicate GameSparksUnity game object.");
		} else {
			instance = this;

  You're welcome ;)

Hey Eduardo,

We actually do suggest using a singleton in our tutorials, however we don't want to commit to inserting this into our code, as we don't know how users want to have the GameSparksUnity.cs script running. They might have slightly different design choices that a singleton might interfere with.
But you are right, this is a good early step when integrating GameSparks with Unity.

Could you do us a favor and turn this into a forum post, so that others might see it if they go searching for similar problems?

Thanks a million,


Sure Sean, right away!

Login to post a comment