Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 vadimcn · Oct 29, 2013 at 09:43 PM · c#eventsingleton

Singleton that can react to game events

I would like to have a "manager"-type singleton object in my game that receives game events like FixedUpdate, Update, LateUpdate, etc. Of course, I can derive it from the MonoBehavior and stipulate that there should one instance of it in a scene (say, attached to the main camera), but this feels hacky and error-prone.

Is there an elegant way of doing this in Unity?

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

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by karlhulme · Oct 30, 2013 at 09:08 AM

Hi vadimcn,

To get the FixedUpdate/Update/LateUpdate game events I think we have no choice but to derive from MonoBehaviour. If so, the problem then becomes how to ensure that we only get one of them. The simplest solution I've found is to have the script check for multiple instances on load as follows:

 public sealed class Manager: MonoBehaviour
 {
     public static Manager Instance { get; private set; }
     
     void Awake()
     {
         if(Instance == null)
         {
             Instance = this;
         }
         else
         {
             throw new System.Exception("too many Manager's in use!");
         }
     }
     
     void Update()
     {
         // check win conditions
     }
         
     void FixedUpdate()
     {
          // check win conditions
     }
     
     public void DoSomething(Vector3 v, string s, int n)
     {
         // change the win conditions
     }
 }

If you accidentally add this component to 2 GameObjects then you'll see errors. This is a clear sign to the designer that something has been setup wrong and hence is easy to fix.

This instancy-singleton can then still be accessed by other code, as follows...

 Manager.Instance.DoSomething(Vector3.up, "hello", 3);

p.s. I think Unity is single-threaded, otherwise you might need a lock statement around Awake to be sure of not getting a second instance.

Comment
Add comment · Show 1 · 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 vadimcn · Nov 04, 2013 at 11:37 PM 0
Share

I was hoping there'd some way to check this at design time, but, oh well... Runtime checks will have to do.

Thanks!

avatar image
0

Answer by rutter · Nov 05, 2013 at 12:04 AM

I tend to use a singleton pattern something like this:

 private Manager _instance;
 public Manager instance {
     get {
         if (_instance == null) {
             _instance = new GameObject("Manager").AddComponent<Manager>();
             Object.DontDestroyOnLoad(_instance);
         }
         return _instance;
     }
 }

The first time anything accesses instance, a Manager will be spawned. All other times, the existing Manager will be used.

Other scripts can then call instance methods:

 Manager.instance.DoSomething();

Depending on your particular needs, it may be advantageous to spawn a prefab instead of just attaching the component.

If you'd rather encapsulate the instance, you can write static methods which access it internally.

You could also use a static constructor, but I've found that can cause errors when interacting with Unity (ie: calls to load resources or attach components tend to fail when called outside of the main thread).

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

17 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

Related Questions

Example of setting up a button OnClick event via scripting? 2 Answers

Relationship between Events and Update() 2 Answers

Distribute terrain in zones 3 Answers

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

Multiple Cars not working 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