Hey guys, I have a game that utilizes procedural generation for levels. There are different base scenes such as ‘Dungeon’ or ‘Town’ which generate a level differently. For testing, it’s easier to run these scenes directly from the editor.
I have a slight annoyance where each of these scenes have an EditorOnly object to run this code when you are on the level, but if i’m going from say a Town to a dungeon in the editor, it will still run that EditorOnly object during testing, causing race condition issues. I can turn off the procedural generation loading editor object off each time I want to go in between levels but that can be kind of annoying.
I was curious if there was a way to tap into the Play Button in the editor, so it will run certain code only when this is the first level entered in the editor. Has anyone done something similar?
Almost… the pattern I like to use for these on-demand services that EVERY level needs (but you don’t want to put crap in every level) is the basic Unity singleton.
Simple Singleton (UnitySingleton):
Some super-simple Singleton examples to take and modify:
These are pure-code solutions, do not put anything into any scene, just access it somewhere in code via the .Instance property.
If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:
public void DestroyThyself()
{
Destroy(gameObject);
Instance = null; // because destroy doesn't happen until end of frame
}