Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Bopsi · Aug 12, 2017 at 06:19 AM · singletonthread

which singleton design pattern should be used ?

hi all, please help me choose the right singleton pattern.

1) i am using a separate class with no Monobehavoiur.

2) Should i use thread safe singleton pattern.

3) Is there any performance hit if i use thread safe singleton pattern.


METHOD 1 : NOT THREAD SAFE

 public sealed class Singleton
 {
     private static Singleton instance = null;
        
     private Singleton()
     {
     }
 
     public static Singleton GetInstance
     {
         get
         {
             if (instance == null)
                 instance = new Singleton();
             return instance;
         }
     }
 }

METHOD2 : THREAD SAFE

 public sealed class Singleton
 {
     private static readonly object obj = new object();
 
     private Singleton()
     {
     }
 
     private static Singleton instance = null;
 
     public static Singleton GetInstance
     {
         get
         {
             if (instance == null)
             {
                 lock (obj)
                 {
                     if (instance == null)
                         instance = new Singleton();
                 }
             }
             return instance;
         }
     }
 }

METHOD 3: THREAD SAFE

 public sealed class Singleton
 {
     private Singleton()
     {
     }
 
     private static readonly Lazy<Singleton> instance = 
                                 new Lazy<Singleton>(()=>new Singleton());
        
     public static Singleton GetInstance
     {
         get
         {
             return instance.Value;
         }
     }  
 }

 


Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by FlaSh-G · Aug 12, 2017 at 12:50 PM

If you don't use Threading, you don't need thread safety here. Unity is single-threaded for all your mono code.

In terms of performance, you'll probably have to run some benchmarks. If you like, here's a little benchmark helper class.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Glurth · Aug 13, 2017 at 07:22 PM 1
Share

Even if you DO use threading, you may NOT access the unity API from another thread. So if that singleton class is implemented on say... a $$anonymous$$onobehavior.. this would also eli$$anonymous$$ate the need for thread safety.

avatar image patarok Glurth · Jan 13, 2021 at 10:08 PM 0
Share

I am asking myself, if that is also true if you use DOTS. If somebody knows(and can explain), I guess it would be appreciated(not only from my side) if you could explain why... (I really dont now much about DOTS, I just heard it brings multithreading...)

avatar image
0

Answer by andycodes · Jan 14, 2021 at 12:30 AM

In addition to what's been said already, I would also like to point out a beneficial use-case of Singletons.

Generally, when I find I need a Singleton, it really ends up acting as more of a Service; I send data to and from, and it helps manage a specific state, and I can call it statically throughout the application. One thing I realized as a result of this is that all my methods can be static, and I don't really have a reason to allow the instance to be public.

For instance, I use this as a currency manager service in one of my projects:

 using System;
 
 public class CurrencyManager
 {
      private static CurrencyManager instance = null;
 
      private int coins; 
         
      private CurrencyManager()
      {
          coins = 0;
      }

      // Notice even GetInstance() is private!
      private static CurrencyManager GetInstance()
      {
         if (instance == null)
         {
             instance = new CurrencyManager();
         }
         return instance; 
     }
 
     public static void Initialize(int previousCurrency)
     {
         CurrencyManager manager = GetInstance();
         Debug.Assert(manager != null);
         manager.coins = previousCurrency;
     }
 
     public static void AddCoins(int amount)
     {
         CurrencyManager manager = GetInstance();
         Debug.Assert(manager != null);
         manager.coins += amount;
     }
 
     public static int GetCurrencyAmount()
     {
         CurrencyManager manager = GetInstance();
         Debug.Assert(manager != null);
         return manager.coins;
     }
 
     public static bool Transact(int cost)
     {
         CurrencyManager manager = GetInstance();
         Debug.Assert(manager != null);
 
         if(manager.coins >= cost)
         {
             manager.coins -= cost;
             return true;
         }
         return false;
     }
 }

I find the benefit to this Design Pattern is that it allows the functionality of the service to be entirely self-contained, and I can still call it universally throughout my application without slipping into the bad practice of having a god-like GameManager that has all-knowing references to major features of the application. I've made this mistake once and I realized it was a bad design decision when I started doing things like GameManager.instance.gameplaymanager.scoremanager..... While I fixed that, and to briefly contradict myself, I still use a GameManager as an all-knowing game initializer to load in data and make sure things are all prepared in a controlled order before allowing the main game scene to fully load. Whether or not it is a good design choice I will only know in time, but so far it's better than it was!

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by logicandchaos · Jan 14, 2021 at 02:44 AM

I would look into scriptable object architecture, you can avoid using singletons altogether.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

72 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Saving last checkpoint hit when reloading scene - Singletons? 1 Answer

singleton, static var, local reference. Whats better? 1 Answer

Create a persistent GameObject using Singleton 3 Answers

Text UI erases after new scene. 1 Answer

Coroutine stops after while-loop 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges