I have a networking client, called Client, that I need to persist between the login scene, character creation scene, and finally the main game scene. I see that DontDestroyOnLoad is not the best practice for creating global objects (at least, according to this: Unity - Manual: Work with multiple scenes in Unity).
I understand the basics behind the scene manager itself. Load scenes additively, unload the old scene, etc. Lets say my main scene has an empty game object with the following script attached.
public class GameManager: Monobehavior {
public Client client;
public void loadScene(string sceneName) { ... }
}
- Does this code basically look right?
- What’s the best practice for accessing the client from anywhere in my application (ie other managers)
- Is the best way to manage scenes to simply call gameManager.loadScene(“Character Creation Scene”) from anywhere (ie after successful login from the “Login Scene”) ?
- Should GameManager be a singleton?
- Code looks good.
- To access your client from anywhere you can define “public static class” or use singletons.
- This is a working approach.
- It could be a singleton.
As in Unity the only way for some code to initialize execution is to be a component of some object in a scene, then you can load a scene holding your Game Manager and mark it as “DontDestroyOnLoad”. Then it should become a “representative” of your game in “Unity world” so handling “Awake”, “Start”, “Update”, “LateUpdate”, “OnDisable”, etc. so allows it to be an “active” subsystem of your game.
If the Game Manager is just a service (so it is just respond to requests, but do not initiate requests), then you can implement it as “static” class:
public static class GameManager {
public static Client client;
public static void loadScene(string sceneName) { ... }
}
and later use it everywhere in your Unity component’s code just calling its methods:
...
GameManager.loadScene("scene_name");
...
And yes, this article is quite fun: http://www.bright-green.com/blog/2003_02_25/naming_java_classes_without_a.html