• 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 t$$anonymous$$s:

 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 t$$anonymous$$s:

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

And accesing the keyCount via "GameVariables.Instance.keyCount"; but Unity says "Object reference not set to an instance of an object." W$$anonymous$$ch doesn't help to ac$$anonymous$$eve 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, t$$anonymous$$s 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, t$$anonymous$$s sounds like a storage only class.
So why make it a MonoBehaviour at all? T$$anonymous$$s 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, t$$anonymous$$s implementation is NOT perfect.
It works in most cases, but when using multithreading, it is not complete.
For more information, see t$$anonymous$$s 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 != t$$anonymous$$s)
         {
             Destroy(t$$anonymous$$s);
             return;
         }
         
         instance = t$$anonymous$$s;
     }
     
     private void OnDestroy()
     {
         // Only empty the instance when it was t$$anonymous$$s
         if (instance == t$$anonymous$$s)
         {
             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 t$$anonymous$$s link: http://wiki.unity3d.com/index.php/Singleton

Greetings
C$$anonymous$$llersanim

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
avatar image chillersanim Bunny83 · Nov 29, 2016 at 08:07 PM 0
Share

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

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

Initialising List array for use in a custom Editor 1 Answer

How to reset all static variables. 5 Answers

Rotation resetted on start 1 Answer

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

How do i delete/ reset unity to its normal settings? 2 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