Home > Back-end >  Doubts about Singletons in unity
Doubts about Singletons in unity

Time:06-13

In my game I have created an object CameraRig, it contains the main camera, also it has 2 scripts, CameraController which controls the movement, rotation, and zoom of the camera and TeamManager which receives a List of units so I can switch the camera position between the members of the team.

I have been trying to pass this CameraRig between my scenes so I think using a singleton is the right thing to do, my doubt is, where do I implement all the code for that?

sorry if this can be a broad question, I'm thankful with any help I can get

CodePudding user response:

You would probably have to use pre-fabs with the scripts attached if you are going to switch scenes as I don't think GameObjects survive scene transition.

You can safely implement singletons in Unity without using static. The idea is that you start off with a blank game manager 3D object (Unity even has the tag "Game Manager" for this purpose) in the scene to which you attach any MonoBehaviours . I call this a soft singleton for want of a better name.

Scene
|--GameObject "Game Manager", tag = "GameManager"
|  |--CameraRig 
|  |--AnotherSingleton
|
. (other scene objects)

Then any script looking for the singleton c# object, instead of looking for the instance of the c# object as we normally would in a c# singleton patterns, you instead query Unity via FindWithTag("GameManager") to get the GameObject then call GetComponent<MySingleton>().

This is a safer way of implementing Unity-compatible singletons rather than using static, something that can be problematic in Unity if care is not taken.

The C# "singleton" behaviour are the result of the GameObject's lifetime not how the C# class is defined and this is also true for all other MonoBehaviour attached to a GameObject.

GameObjects should always be in control of a MonoBehaviour's and child object's lifetime. Using static essentially leads to orphaned objects created adhoc.

CodePudding user response:

If you want to share some monobehaviour across different scenes, you can use the so-called "monosingleton". By calling DontDestroyOnLoad() you tell unity not to destroy object when another scene is loading.

Here is an example of such pattern implementation.

  • Related