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
3
Question by fherbst · Aug 15, 2011 at 05:32 PM · editorplaymodesingleton

Singleton and MonoBehaviour in Editor

Hello all,

I'm using a simple singleton pattern in a script:

 public class EasySingleton {
   private static EasySingleton instance = null;
   public static EasySingleton Instance { get { return instance; } }
 
   void Awake() {
     instance = this;
   }
 }

Everything in-game works fine, but there is one annoying thing when working in the editor: if I press Play, make some code changes, and click back in the game view, I get NullReferenceExceptions when accessing "instance". Normally, such on-the-fly code editing works fine.

So my questions are: what events get called when switching from play mode to code and back without stopping the game before? How can I optimize such a singleton pattern to work smoothly in the editor? Does this work better with another singleton pattern?

Best regards, Felix

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

1 Reply

· Add your reply
  • Sort: 
avatar image
6
Best Answer

Answer by Bunny83 · Aug 15, 2011 at 06:33 PM

Yep, usually i use this one:

 private static EasySingleton instance = null;
 public static EasySingleton Instance
 {
     get
     {
         if (instance == null)
             instance = (EasySingleton)FindObjectOfType(typeof(EasySingleton));
         return instance;
     }
 }

To be on the absolute safe side you could implement a second check to create it if it's not found

 get
 {
     if (instance == null)
     {
         instance = (EasySingleton)FindObjectOfType(typeof(EasySingleton));
         if (instance == null)
             instance = (new GameObject("EasySingleton")).AddComponent<EasySingleton>();
     }
     return instance;
 }
Comment
Add comment · Show 6 · 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 Bunny83 · Aug 15, 2011 at 06:41 PM 0
Share

The problem is that when you change something during runtime Unity recompiles all scripts and therefore have to recreate every object instance. Unity uses it's own internally serialisation function to "save" the old state and to restore it after the objects are recreated. But Unity doesn't serialize everything so you will loose all non serialized fields. As long as you only use serialized fields (public or [SerializeField]) it should be ok.

avatar image fherbst · Aug 16, 2011 at 03:27 PM 0
Share

Yep, thats what I currently do - check if the singleton != null. Double-checking and creating if not existant is a nice idea, thanks.

avatar image GermanViscuso · Dec 10, 2013 at 11:23 PM 0
Share

Thanks Bunny83 this saved my life!

avatar image Lypheus · Feb 10, 2015 at 05:54 PM 0
Share

Double checked locking is a BAD idea : http://stackoverflow.com/questions/394898/double-checked-locking-in-net

Ins$$anonymous$$d, the simplest and best approach is: https://msdn.microsoft.com/en-us/library/ff650316.aspx

avatar image Bunny83 · Feb 13, 2015 at 02:58 AM 0
Share

@Lypheus: Your two links are not relevant here because:

  • $$anonymous$$y implementation doesn't have a double checked locking since i don't lock at all. Look at my examples carefully.

  • Unity's classes / interfaces aren't thread safe so usually multiple threads aren't be used.

  • The implemenation presented on those sites you've linked simply use the "new" keyword to create an instance. In Unity you can't create an instance of a component with "new". You have to use AddComponent on a GameObject. That's what i do in my second example.

  • The usual implementations of Singletons in Unity are singletons which are represented by serialized objects. Like you can see in the question the OP had such a case. He used the Awake callback to initialize the variable.

  • All those "double checked locking is bad" articles only talk about a multithreaded environment which is not relevant here since "FindObjectOfType" as well as "new GameObject" and "AddComponent" can only be executed on the main thread. So there's no way to implement a thread-safe version of a Component-based singleton in Unity.

Show more comments

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

[Unity Editor] Emulate Touch Input - Still Asking 12/10 1 Answer

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Unity Editor Playmode Tint Change by Script 4 Answers

How can I preserve static object/data between editor and play? 2 Answers

Is the animator graph editor exposed to the API? Unity 4.0 0 Answers


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