Skip to content

Instantly share code, notes, and snippets.

@stash
Created March 30, 2018 22:18
Show Gist options
  • Save stash/8d5f895e6c0ae3458e35ac4eeb20e345 to your computer and use it in GitHub Desktop.
Save stash/8d5f895e6c0ae3458e35ac4eeb20e345 to your computer and use it in GitHub Desktop.
GlobalObject.cs
using UnityEngine;
/**
* Singleton-esque inter-Scene GameObject loader.
*
* Ever wanted a singleton or global sort of GameObject that still allowed for editing properties in the Unity Editor?
* I sure did, for things like background music, a game controller, etc. So, I made this simple system of creating a global or "inter-scene" GameObject. It's not a true singleton, but it does a good job at ensuring there's only GameObject with this script attached. I don't like the approach of creating a persistent, additively-loaded scene -- not to mention the other approaches to making true Singleton objects -- so I've opted for a pre-fabbable GameObject approach.
*
* HowTo, in the Unity Editor (tested with 2017.3.1f1):
* 1. Attach this script to an empty GameObject in the current scene.
* 2. Add any other global game objects as children of this one.
* 3. Create a prefab of this object.
* 4. Go to Edit > Project Settings > Script Execution Order
* 5. Add this script to the list by clicking the "+" button
* 6. In the numeric field, enter -1 or below so this runs before any other script you might have. Save this setting.
* 7. Add the prefab to all scenes & every new scene you create.
*
* If other scripts run before this one, and there's inter-dependencies between those scripts, then it's possible that the scripts will get the wrong object when calling, e.g., FindObjectOfType<>(). This is why you need to set a low number in the Script Execution Order list.
*/
public class GlobalObject : MonoBehaviour {
private static GlobalObject instance;
private void Awake() {
if (!instance) {
Debug.Log(gameObject.name + " Awake, becoming global");
DontDestroyOnLoad(gameObject);
instance = this;
} else {
Debug.Log(gameObject.name + " Awake, self-destructing");
DestroyImmediate(gameObject);
}
}
}
@stash
Copy link
Author

stash commented Mar 30, 2018

image

@stash
Copy link
Author

stash commented Mar 30, 2018

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment