Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

skinitimski commented Mar 12, 2020

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.

Loading

@tomlarkworthy
Copy link
Author

tomlarkworthy commented Mar 12, 2020

Loading

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