Auto-boot your Unity game when entering Play mode

April 10, 2018

I am working on a game. There are a lot of games like it, but this one is mine.

TL:DR; The code is at the bottom ;)

Early on in development, I decided that I would split the game up into distinct scenes, and load each scene when I needed it. The alternatives would be to create one scene and have everything inside it, or create lots of prefabs and load those when I need to. But I chose not to use those alternatives.

So that meant that I created scenes that you may remember, such as “Bootstrap”, “Game”, “Credits” and so on.

The Bootstrap scene takes care of the initial configuration of the game’s support systems, such as initialising logging and event systems; this means that it is THE first class citizen which MUST be loaded before any other scene.

All was well, for a while. But then I hit a snag.

Every time I wanted to play test, I would have to save the scene that I was currently working on, and then look through the hierarchy to find the Bootstrap scene. Once I found it, I would launch it, then run the game and do my play test. After that, I would stop the game, go back to the hierarchy, find the scene I was working on before, launch it, then continue working.

Rinse and repeat. Rinse and repeat.

Eventually I got frustrated. I thought I could solve the issue by writing some menu items, complete with hotkeys, that would allow me to easily switch scenes; but the downsides were obvious — for each scene I added I would need to add a new entry into the menu items editor script, or I could write a code generator to generate the script for me, but I would still be manually switching scenes.

So I decided to do some research on automatically switching scenes when entering Play mode. Luckily, there were quite a few scripts and forums out there that did what I wanted; unfortunately, they were either too old, or had way more functionality than I wanted. Plus, I wanted to have a stab at it myself.

Below is what I came up with; its fairly simple. It has an InitializeOnLoad tag so no need to instantiate it, Unity will take care of that. When you hit Play, it grabs the currently loaded scenes and stores them in a list in the EditorPrefs. Then it opens a scene that is manually defined at the top of the script (hey, I only have one bootstrap scene, and it’s not going to change). When you exit Play mode, it iterates through the stored list, opening the first scene to clear the currently loaded scene, then opens any other scenes additively, so that you end up back in the scenes where you started.

Without further ado:

Hopefully someone else finds this useful, or at least finds it a useful starting point. Suggestions are more than welcome.

comments powered by Disqus