Skip to content

Instantly share code, notes, and snippets.

@tomlarkworthy
Last active October 2, 2022 18:15
Show Gist options
  • Save tomlarkworthy/11e0d99f69761ca5dd248e67fd398faf to your computer and use it in GitHub Desktop.
Save tomlarkworthy/11e0d99f69761ca5dd248e67fd398faf to your computer and use it in GitHub Desktop.
Example of the Stateless Scene pattern (see https://corepox.net/devlog/unity-pattern:-stateless-scenes)
void loadMyScene(MySceneParams params, System.Action<MySceneOutcome> callback)
using UnityEngine;
public class MySceneBehaviour: MonoBehaviour {
private static MySceneParams loadSceneRegister = null;
public MySceneParams sceneParams;
public static void loadMyScene(MySceneParams sceneParams, System.Action<MySceneOutcome> callback) {
MySceneBehaviour.loadSceneRegister = sceneParams;
sceneParams.callback = callback;
UnityEngine.SceneManagement.SceneManager.LoadScene("MyScene");
}
public void Awake() {
if (loadSceneRegister != null) sceneParams = loadSceneRegister;
loadSceneRegister = null; // the register has served its purpose, clear the state
}
public void endScene (MySceneOutcome outcome) {
if (sceneParams.callback != null) sceneParams.callback(outcome);
sceneParams.callback = null; // Protect against double calling;
}
}
[System.Serializable]
public class MySceneParams {
public System.Action<MySceneOutcome> callback;
// + inputs of the scene
}
public class MySceneOutcome {
// + outputs of the scene
}
void testMyScene() {
MySceneBehaviour.loadMyScene(new MySceneParams(/* ... */), (outcome) => {
Debug.Log("Scene over " + outcome.ToString());
});
}
@tomlarkworthy
Copy link
Author

tomlarkworthy commented Mar 12, 2020 via email

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