Hi guys! I'm having a bit of an issue with my scene load and reload for my multilevel game. Every time I beat a level in my game and change the scene, a duplicate of my Main camera is made. This messes with all of my screentoworld stuff with my mouseposition and aiming of my player. How can I make sure that a second main camera isn't created when I load a scene?
cameras cannot create them themself. Do you use DontDestroyOnLoad ? Or something in new level add new camera.
Use singleton construction pattern, inside your camera script to have only one instance of your camera. It will fix your problem of duplication. If you have other duplication problem like player or gamemanager use singleton! Code (CSharp): public class Camera2D : MonoBehaviour { //Singleton private static Camera2D _instance; public static Camera2D Instance { get { return _instance; } } private void Awake() { //Singleton if (_instance != null && _instance != this) { Destroy(this.gameObject); } else { _instance = this; } } }
I am very aware of singletons, but only recently started working with multi-scene setup, had "Multiple audio listeners" message spamming the console every frame and realizing that I'm not doing anything special in terms of the workflow, so I started looking around for what is the correct way to handle this. Apparently, making a custom singleton is the way. Which makes sense. I've added mine below if anyone is interested. Could be reused for many objects by expanding the enum. Code (CSharp): public class GameObjectSingleton : MonoBehaviour { [SerializeField] private SingletonRole _role; private enum SingletonRole { MainCamera = 0, Canvas = 1, Player = 2 } private static Dictionary<SingletonRole, GameObject> _inTheScene = new Dictionary<SingletonRole, GameObject>(); private void Awake() { if (_inTheScene.TryGetValue(_role, out GameObject go) && go && go != gameObject) { Destroy(gameObject); } else { _inTheScene[_role] = gameObject; } } }