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
1
Question by Paramotion · Nov 29, 2016 at 01:42 PM · startresetcollectiblestatic variables

Force reset static variable

After googling a bit, I've tried some methods to try to reset a static variable, but none of them want to work (Sure I'm doing some wrong steps). First I tried to Reset the value to 0, both via Start, and Update, like this:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class GameVariables : MonoBehaviour  {
 
     public static int keyCount;
     public static int resetkeyCount = 0;
 
     void Start () {
             keyCount = resetKeyCount;
     }
     void Update () {
         if (Input.GetKeyDown(KeyCode.Escape)) {
             Reset();
         }
     }
     void Reset (){    
             keyCount = resetKeyCount;
         }
     }

And after by trying to instantiate the Class, like this:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class GameVariables : MonoBehaviour  {
     
         public static GameVariables Instance;
         public int keyCount;
     
 
     void Start () {
             Instance = this;
     }
 }

And accesing the keyCount via "GameVariables.Instance.keyCount"; but Unity says "Object reference not set to an instance of an object." Which doesn't help to achieve the goal.

Since the objective for the player is collecting "X" keys, the goal with the code is to reset the keyCount each time the scene is loaded.

If anyone has an idea of how to proceed, it'll be great.

Thanks in advance.

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
2
Best Answer

Answer by chillersanim · Nov 29, 2016 at 02:32 PM

It looks like you are trying to implement a singleton behaviour.
If so, this code of yours is not complete. The problem you face, is that the Instance variable may not be set when you access it.
I assume you access it from outside the class?

Possible solution:
A way around would be, to create a public static property, with only a get-accessor.
When the property is accessed, it should check whether an instance exists, if not, it should create one.
Only then it should give that instance back.

Taking a step back:
Your class is called GameVariables, this sounds like a storage only class.
So why make it a MonoBehaviour at all? This restricts your use alot.
If you don't need the class to inherit from MonoBehaviour, I would sugest to just create a static class, inheriting from object.

Example:

 public class GameVariables
 {
     private static GameVariables instance;
 
     public static GameVariables Instance
     {
         get
         {
             // Returns instance. Or if null, creates new instance, stores it and returns it.
             return instance ?? (instance = new GameVariables());
         }
     }
     
     // Private in order to prevent multiple instances
     private GameVariables()
     {
         // Initialize instance here
     }
 }

Be aware, this implementation is NOT perfect.
It works in most cases, but when using multithreading, it is not complete.
For more information, see this link: https://msdn.microsoft.com/en-us/library/ff650316.aspx

Edit:
If you realy need a MonoBehaviour singleton, the code would look a little different:

 public class GameVariables : MonoBehaviour
 {
     private static GameVariables instance;
     
     public static GameVariables Instance
     {
         get
         {
             if (instance == null)
             {
                 // Create new GO and add component
                 var go = new GameObject();                                
                 instance = go.AddComponent<GameVariables>();
             }
             
             return instance;
         }
     }
     
     private void OnEnable()
     {    
         // Prevent game developer from instantiating multiple singletons...
         if (instance != null && instance != this)
         {
             Destroy(this);
             return;
         }
         
         instance = this;
     }
     
     private void OnDestroy()
     {
         // Only empty the instance when it was this
         if (instance == this)
         {
             instance = null;
         }
     }
 }

Here again, the code is NOT perfect.
If you use multithreading or access the singleton when the application is quitting, it could cause errors.
For more information, see this link: http://wiki.unity3d.com/index.php/Singleton

Greetings
Chillersanim

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 Bunny83 · Nov 29, 2016 at 06:42 PM 1
Share

Your implementation wouldn't work. A static class can't be instantiated and can only contain static members (static methods, fields, properties). If you want to implement a singleton, the class must not be static.

avatar image chillersanim Bunny83 · Nov 29, 2016 at 08:07 PM 0
Share

Whops, you are right.
I've written the code from the top of my head, but that's a stupid one...
Anyways, I've fixed it. Thanks :)

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

Rotation resetted on start 1 Answer

Initialising List array for use in a custom Editor 1 Answer

Collectibles Objects and Resetting game after all are collected in javascript? 1 Answer

How to reset all static variables. 5 Answers

Problem naming instances with incrementally numbered counter 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