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());
});
}
@skinitimski
Copy link

I read "a functional approach" and I got excited. I'm very new to Unity and just use it for fun. But in my day job I do a lot of functional coding, so I find it odd that I can't (for example) pass any context (other than a starting position and parent) to objects that I create with Instantiate.

So far I've been going with the static-singleton approach but started looking at representing everything as addressables instead, and global state became problematic immediately. I don't even like global state, so this might be a worthy alternative. I will give it a try.

@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