Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 LineKernel · Apr 17, 2016 at 12:22 PM · nullreferenceexceptionsingleton

ToolBox singleton nullreferenceexception on reloading scene

Hi , i m trying singleton for the first time and i cant get rid of the null ref exception on reloading of the scene , i saw post where people get already destroyed problem with application quit , but it s not the same i get

so i have the toolbox setup

 using UnityEngine;
 using System.Collections;
 
 public class Toolbox : Singleton<Toolbox> {
     protected Toolbox () {} // guarantee this will be always a singleton only - can't use the constructor!
  
     //public string myGlobalVar = "whatever";
      public bool allRaycastDebugOn = false;
      public bool allRaycastDepth = false;
      public bool RandomSeed = false;
      public string seed ;
     //public Language language = new Language();
  
     void Awake () {
         // Your initialization code here
 
     }
  
     // (optional) allow runtime registration of global objects
     static public T RegisterComponent<T> () where T: Component {
         return Instance.GetOrAddComponent<T>();
     }
 }

the singleton

 using UnityEngine;
 using System.Collections;
  
 /// <summary>
 /// Be aware this will not prevent a non singleton constructor
 ///   such as `T myT = new T();`
 /// To prevent that, add `protected T () {}` to your singleton class.
 /// 
 /// As a note, this is made as MonoBehaviour because we need Coroutines.
 /// </summary>
 public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
 {
     private static T _instance;
  
     private static object _lock = new object();
  
     public static T Instance
     {
         get
         {
             if (applicationIsQuitting) {
                 Debug.LogWarning("[Singleton] Instance '"+ typeof(T) +
                     "' already destroyed on application quit." +
                     " Won't create again - returning null.");
                 return null;
             }
  
             lock(_lock)
             {
                 if (_instance == null)
                 {
                     _instance = (T) FindObjectOfType(typeof(T));
  
                     if ( FindObjectsOfType(typeof(T)).Length > 1 )
                     {
                         Debug.LogError("[Singleton] Something went really wrong " +
                             " - there should never be more than 1 singleton!" +
                             " Reopenning the scene might fix it.");
                         return _instance;
                     }
  
                     if (_instance == null)
                     {
                         GameObject singleton = new GameObject();
                         _instance = singleton.AddComponent<T>();
                         singleton.name = "(singleton) "+ typeof(T).ToString();
  
 //                        DontDestroyOnLoad(singleton);
 // 
                         Debug.Log("[Singleton] An instance of " + typeof(T) + 
                             " is needed in the scene, so '" + singleton +
                             "' was created with DontDestroyOnLoad.");
                     } else {
 //                        DontDestroyOnLoad(_instance.gameObject);
 //                        
                         Debug.Log("[Singleton] Using instance already created: " +
                             _instance.gameObject.name);
                     }
                 }
  
                 return _instance;
             }
         }
     }
  
     private static bool applicationIsQuitting = false;
     /// <summary>
     /// When Unity quits, it destroys objects in a random order.
     /// In principle, a Singleton is only destroyed when application quits.
     /// If any script calls Instance after it have been destroyed, 
     ///   it will create a buggy ghost object that will stay on the Editor scene
     ///   even after stopping playing the Application. Really bad!
     /// So, this was made to be sure we're not creating that buggy ghost object.
     /// </summary>
     public void OnDestroy () {
         applicationIsQuitting = true;
     }
 }

the methodeextention

 using UnityEngine;
 using System.Collections;
 
 static public class MethodExtensionForMonoBehaviourTransform {
     /// <summary>
     /// Gets or add a component. Usage example:
     /// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
     /// </summary>
     static public T GetOrAddComponent<T> (this Component child) where T: Component {
         T result = child.GetComponent<T>();
         if (result == null) {
             result = child.gameObject.AddComponent<T>();
         }
         return result;
     }
 }

first script to get the seed string from my toolbox

 using UnityEngine;
 using System.Collections;
 
 public class ToolBoxTester : MonoBehaviour {
 
     // Use this for initialization
     void Start () {
         //Toolbox toolbox = Toolbox.Instance;
         print("seed = " + Toolbox.Instance.seed);
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 }
 

and a script that restart the scene on keypress

 using UnityEngine;
 using System.Collections;
 
 public class RestartGame : MonoBehaviour {
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         if(Input.GetKeyDown(KeyCode.N)){UnityEngine.SceneManagement.SceneManager.LoadScene(PlayerPrefs.GetInt("currentscenesave"));}//Application.LoadLevel(0);}
     }
 }

at start everything is fine , i get my seed printed out but ; when i press the reloadmyscene button i get the error

 NullReferenceException: Object reference not set to an instance of an object
 ToolBoxTester.Start () (at Assets/Scripts/ToolBoxTester.cs:9)
 

 

my question is , what should i do to not get this error

thanks

alt text

[EDIT]

i have the feeling that my problem is related to if (applicationIsQuitting) {return null;} in the singleton ; i m tempted to cut it out of the code , but then i dont know how i would be able to detect if i have a buggy ghost object in my scene .

[/EDIT]

screenshot-925.png (296.9 kB)
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
0
Best Answer

Answer by LineKernel · Apr 26, 2016 at 01:30 PM

this is a duplicate http://answers.unity3d.com/questions/624427/using-toolbox-singleton-script-and-reloading-scene.html

the last answer by JASlaughter is working

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Singleton good in one project but null references in other 1 Answer

Nullreferenceexception when singleton called by object loaded from previous scene that had another copy of that singleton 2 Answers

Problem with Singleton and NullReferenceException? 0 Answers

Data from a simple singleton / static class return null 1 Answer

Null reference exception - singletone 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