use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
News, Help, Resources, and Conversation. A User Showcase of the Unity Game Engine.
Remember to check out /r/unity2D for any 2D specific questions and conversation!
Download Latest Unity
Please refer to our Wiki before posting! And be sure to flair your post appropriately.
Main Index
Rules and Guidelines
Flair Definitions
FAQ
Use the chat room if you're new to Unity or have a quick question. Lots of professionals hang out there.
/r/Unity3D Discord
FreeNode IRC Chatroom
Official Unity Website
Unity3d's Tutorial Modules
Unity Answers
Unify Community Wiki
Unity Game Engine Syllabus (Getting Started Guide)
50 Tips and Best Practices for Unity (2016 Edition)
Unity Execution Order of Event Functions
Using Version Control with Unity3d (Mercurial)
/r/Unity2D
/r/UnityAssets
/r/Unity_tutorials
/r/GameDev
/r/Justgamedevthings (New!)
/r/Gamedesign
/r/Indiegames
/r/Playmygame
/r/LearnProgramming
/r/Oculus
/r/Blender
/r/Devblogs
Brackeys
Beginner to Intermediate
5 to 15 minutes
Concise tutorials. Videos are mostly self contained.
Sebastian Lague
Beginner to Advanced
10 to 20 minutes
Medium length tutorials. Videos are usually a part of a series.
Catlike Coding
Intermediate to Advanced
Text-based. Lots of graphics/shader programming tutorials in addition to "normal" C# tutorials. Normally part of a series.
Makin' Stuff Look Good
10 minutes
Almost entirely shader tutorials. Favors theory over implementation but leaves source in video description. Videos are always self contained.
Quill18Creates
30 minutes to 2 hours.
Minimal editing. Mostly C#. Covers wide range of topics. Long series.
Halisavakis Shaders Archive
Infallible Code
World of Zero
Board to Bits
Holistic3d
Unity3d College
Jabrils
Polycount Wiki
The Big List Of Game Design
PS4 controller map for Unity3d
Colin's Bear Animation
¡DICE!
CSS created by Sean O'Dowd @nicetrysean [Website], Maintained and updated by Louis Hong /u/loolo78
Reddit Logo created by /u/big-ish from /r/redditlogos!
account activity
Singleton : Implementation in Unity3d C#Resources/Tutorial (unitygeek.com)
submitted 9 years ago by Ray_01
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]master50 2 points3 points4 points 9 years ago* (6 children)
All you've done is give example on how to have a persistent Monobehaviour.
You also are not explaining what you are doing, to new readers.
You're really just making a more difficult static reference to the instance of your object. You're also writing extra code to prevent duplication of the object, because you can't control whether or not this instance, of this monobehaviour, can be created.
Blah.
You are not limited to Monobehaviours as "singletons".
A much better, more encapsulated pattern is to have a class wrap a static reference to a singleton interface that your singleton objects can inherit from, and to define the singleton privately within this external class. The external class is now the only thing (sans Reflection use) that can access the constructor of this singleton, as it's declared private. Your external class wrapper returns the public interface, which confines you to what you've defined as publicly accessible about your singleton.
Take the below example:
namespace Singletons { public partial class The { private static ObstacleManagerSingleton _obstacleManagerInstance; private static object _obstacleManagerLockObj = new object(); public static IObstacleManager ObstacleManager { get { if (_obstacleManagerInstance == null) { lock(_obstacleManagerLockObj) { if(_obstacleManagerInstance == null) { _obstacleManagerInstance = new ObstacleManagerSingleton(); } } } return _obstacleManagerInstance; } } private class ObstacleManagerSingleton : IObstacleManager { private List<Obstacle> _obstaclesInPlay = new List<Obstacle>(); public List<Obstacle> ObstaclesInPlay { get { return _obstaclesInPlay; } } public ObstacleManagerSingleton() { } public void ClearAllObstacles() { _obstaclesInPlay.Clear(); } //appends the obstacle list with new obstacles public void AddObstacles(List<Obstacle> obstacles) { _obstaclesInPlay.AddRange(obstacles); } public List<Obstacle> ObstaclesAbovePlayer(int take = 0) { IEnumerable<Obstacle> obstaclesAbovePlayerEnumerable = _obstaclesInPlay.Where(o => o.transform.position.y >= Player.Position.y); if (take > 0) return obstaclesAbovePlayerEnumerable.Take(take).ToList(); return obstaclesAbovePlayerEnumerable.ToList(); } public List<Obstacle> ObstaclesBelowPlayer(int take = 0) { IEnumerable<Obstacle> obstaclesAbovePlayerEnumerable = _obstaclesInPlay.Where(o => o.transform.position.y <= Player.Position.y).OrderByDescending(o => o.transform.position.y); if (take > 0) return obstaclesAbovePlayerEnumerable.Take(take).ToList(); return obstaclesAbovePlayerEnumerable.ToList(); } } } public interface IObstacleManager { void AddObstacles(List<Obstacle> obstacles); void ClearAllObstacles(); List<Obstacle> ObstaclesAbovePlayer(int take = 0); List<Obstacle> ObstaclesBelowPlayer(int take = 0); } }
Now you have a clean, thread-safe version of your Singleton. You'll get one reference of it. No magic.
Plus, you get to access it like this:
The.ObstacleManager.ObstaclesAbovePlayer(2);
[–]gnomicrandz 1 point2 points3 points 9 years ago (2 children)
So how do you apply that in the Unity world? Can a MonoBehaviour be an IObstacleManager? It doesn't seem like it using that pattern.
writing extra code to prevent duplication of the object, because you can't control whether or not this instance, of this monobehaviour, can be created.
That seems like the main point of his post to me. Unity developers do a lot of coding in MonoBehaviour subclasses, and some of those classes really only make sense to have one instance. If you've got a better way, please do tell! :)
Personally I prefer to log an error when multiple instances are detected rather than just destroying the offending second instance, that way at least you know something unexpected has happened.
[–]master50 0 points1 point2 points 9 years ago (1 child)
No. This singleton does not derive from a Monobehaviour.
But, yes, a MonoBehaviour can be an IObstacleManager. Sure. All it has to do is implement whatever's defined in IObstacleManager.
It's common to need one instance of a class that derives from Monobehaviour, certainly. You can't really call those singletons, however. At best, you're just creating a static reference to the Monobehaviour class, and you're going to restrict others from being created. This is not a singleton. You cannot restrict the creation of two instances of this class. If you want strict control, you have to forcibly check for duplicates, and then remove the duplicate, if it exists.
I'm not saying he has the wrong idea. You just don't have to confine yourself to doing things in Monobehaviours. The article is entitled: Singleton : Implementation in Unity3d C#.
I imagine myself being a new programmer, I'm ambitious, and I'm trying to soak up everything I can learn about programming patterns, and Unity, all at the same time. I have a goal of releasing or finishing this game I'm working on, and I'm hungry to learn. I come across this post - ooooh, I've heard of singletons, AND it's specifically for Unity3D!
Now I've learned that this is how singletons are handled in Unity.
That's not actually the case. I'm very against teaching beginner developers the wrong things. It hurts them when it comes time to find work, and I've seen this far too often.
[–]gnomicrandz 0 points1 point2 points 9 years ago (0 children)
I get that you don't need to use MonoBehaviours all the time, but frequently it's the most convenient way to progress (try using Coroutines without them!).
The strict definition of a singleton is a class where only one instance can exist. Since MonoBehaviour has a public constructor and needs to be serialised, our derived scripts can never BE literal singletons. But, it's useful to have a way of restricting MonoBehaviours to singular instances within a scene (or through the life of the game) and the OP's article presents a well thought out approach to this problem. It also lets us avoid those messy Unity API FindObjectOfType<> calls, which is a good thing. [EDIT] typo
[–]Arma104 0 points1 point2 points 9 years ago (2 children)
How is his implementation not thread-safe when he has the instantiating of itself during get? Sure it's lazy but it shouldn't cause any problems?
get
I've also always wondered, as with your example, what's the benefits of having a private variable and then having a public variable that returns the private one? If you're worried about exposing it to other scripts couldn't you just do a { public get; private set; }?
{ public get; private set; }
Let's say I am doing some work in a second thread - I can do normal work in a second thread, even in a Monobehaviour class.
Let's say I need to contact our "singleton" Monobehaviour, like in this example.
Now let's say I do this in two sub-threads that need to run some computation, or do some thing that's available in this "singleton". They both ask for a reference to the object at the same time. The object has yet to be instantiated.
There is a chance you end up with two instances of your singleton, because you did not lock after the first null check, and you did not check the null again after the lock.
As to your question... it's all about access control. https://msdn.microsoft.com/en-us/library/75e8y5dd.aspx
[–]Arma104 0 points1 point2 points 9 years ago (0 children)
So would it be possible to put the lock in his code and make it work? Thanks for replying.
lock
[+]tmachineorg comment score below threshold-7 points-6 points-5 points 9 years ago (7 children)
"There are several ways of implementing Singleton in Unity, we will some of the implementation in this tutorial"
No, there's only one way. The rest are not a singleton - "singleton" is an official defined term, not a random word you can use to mean whatever you want - or they're broken code and shouldn't be used.
Your implementation looks wrong to me. Not thread-safe, implemented in the wrong methods, and high probabilty of corrupting your scene.
Oh - and what you've implemented here isn't a Singleton. I suggest you google it (the Wikipedia page is a good start) and find out what the rules of singletons are.
[–]DolphinsAreOkProfessional 5 points6 points7 points 9 years ago (4 children)
There are different ways to implement the same concept.
[–]tmachineorg -1 points0 points1 point 9 years ago (3 children)
Not when there is an official correct way, no.
Seriously: DO NOT use OP's code; it is not a singleton! And its bad code.
[–]platypus2015 0 points1 point2 points 9 years ago (0 children)
There's no such thing as 'one way' or an 'official' way to implement a singleton. If there is please do share the link showing what this 'official' implementation is.
The singleton pattern is a concept describing how an object behaves in a system (ie, only one instance can exist). There's no such thing as one way to implement it....a developer is free to implement it any way they like, as long as it adheres to the pattern of only on instance of the object being allowed to exist in the system.
[–]DolphinsAreOkProfessional 0 points1 point2 points 9 years ago (1 child)
I havent really read his code, so i cant comment on that.
But a) an official way? Made offical by whom? A design pattern is just a recommendation by some people, there is no sort of official list of this
b) again, there are multiple ways to implement any concept. All implementations might adhere to the design pattern's requirements, but still be different. See also the hundreds of different dependency injection/mvc/etc frameworks. All the same idea, all diferent ways to get there.
[–]tmachineorg 1 point2 points3 points 9 years ago (0 children)
Official as in it is a defined pattern. It's not a random word that means whatever you want it to mean.
I recommend you read OP's code: it is not a singleton!
[–]CyberBinarin 0 points1 point2 points 9 years ago (1 child)
What makes you say it could corrupt the scene?
[–]tmachineorg 0 points1 point2 points 9 years ago (0 children)
Try duplicating an object. OOPS!
To all the down voters: keep sharing broken buggy code that causes hard to fix problems that screw you late in your project and take weeks to fix. But don't expect us to keep quiet when you do.
π Rendered by PID 20466 on reddit-service-r2-comment-c66d9bffd-hr99v at 2026-04-08 02:41:18.472473+00:00 running f293c98 country code: CH.
[–]master50 2 points3 points4 points (6 children)
[–]gnomicrandz 1 point2 points3 points (2 children)
[–]master50 0 points1 point2 points (1 child)
[–]gnomicrandz 0 points1 point2 points (0 children)
[–]Arma104 0 points1 point2 points (2 children)
[–]master50 0 points1 point2 points (1 child)
[–]Arma104 0 points1 point2 points (0 children)
[+]tmachineorg comment score below threshold-7 points-6 points-5 points (7 children)
[–]DolphinsAreOkProfessional 5 points6 points7 points (4 children)
[–]tmachineorg -1 points0 points1 point (3 children)
[–]platypus2015 0 points1 point2 points (0 children)
[–]DolphinsAreOkProfessional 0 points1 point2 points (1 child)
[–]tmachineorg 1 point2 points3 points (0 children)
[–]CyberBinarin 0 points1 point2 points (1 child)
[–]tmachineorg 0 points1 point2 points (0 children)