Reputation: 46
I put all the managers in the game on an empty scene called Init. The editor must be run from this scene for the game to work properly. So I want to write an editor script that loads the Init scene first and then loads the level scene.
My editor script:
[InitializeOnLoad]
public class LevelFix
{
static LevelFix()
{
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
switch (state)
{
case PlayModeStateChange.ExitingEditMode:
bool initCheck = true;
int sceneCount = SceneManager.sceneCount;
Scene lastLevel = SceneManager.GetActiveScene();
for (int i = 0; i < sceneCount; i++)
{
Scene scene = SceneManager.GetSceneAt(i);
if (scene.name.Contains("Level"))
{
initCheck = false;
}
}
if (!initCheck)
{
PlayerPrefs.SetString("LastLevel", lastLevel.name);
}
break;
case PlayModeStateChange.EnteredPlayMode:
SceneManager.LoadScene(0); //Init Scene
break;
}
}
}
Init Manager responsible for the level to be loaded (Located in Init scene):
public class InitManager : MonoBehaviour
{
private IEnumerator Start()
{
yield return SceneManager.LoadSceneAsync(PlayerPrefs.GetString("LastLevel", "Level01"), LoadSceneMode.Additive);
SceneManager.SetActiveScene(SceneManager.GetSceneByName(PlayerPrefs.GetString("LastLevel", "Level01")));
Destroy(gameObject);
}
}
The problem with the code above is that whichever level I run, first that level opens and then Init opens. This situation causes some errors. Is there any way to set the scene to be loaded before the editor entered play mode?
Upvotes: 3
Views: 3414
Reputation: 26547
Yes, Unity provides a very simple way to load a specific scene when entering Play Mode with EditorSceneManager.playModeStartScene
:
[InitializeOnLoad]
public class SetStartScene {
static SetStartScene() {
EditorSceneManager.playModeStartScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(scenePath);
}
}
Upvotes: 2