How to use Singletons in unity?

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

Upvotes: 0

Views: 1301

Answers (2)

Morion
Morion

Reputation: 10860

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 an object when another scene is loading and the static variable allows you to have access to this instance from any piece of code in your project.

Here is an example of such pattern implementation.

Upvotes: 1

user585968
user585968

Reputation:

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.

Upvotes: 1

Related Questions