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 spinnerbox · Dec 22, 2015 at 03:47 PM · saveloadsingletondata storagepersistence

Keep Singleton while creating holder GameObject at runtime?

I used the persistence tutorial to create SIngleton of my game state object and it all works well. I also found that I need to create manually GameObject on scene, so that I have where to attach the game state script. Then I got to idea, what if I create the holder object at runtime using "new GameObject()" and than "AddComponent()" function. Is my Singleton pattern still kept across scenes or I am recreating this game state object every time I enter a new scene?

Game state code:

 using UnityEngine;
 using System;
 using System.Runtime.Serialization.Formatters.Binary;
 using System.IO;
 
 public class SaveLoadGameData : MonoBehaviour 
 {
     public static SaveLoadGameData gameState;
     
     public float experience = 0;
     public float score = 0;
     
     void Awake () 
     {
         if (gameState == null) 
         {
             DontDestroyOnLoad(gameObject);
             gameState = this;
         }
         else if (gameState != this) 
         {
             Destroy(gameObject);
         }
     }
     
     public void Save ()
     {
         // saving code
     }
     
     public void Load ()
     {
         // loading code
     }
     
     public void ResetGameState ()
     {
         // reset data to defaults and save.
     }
 }
 
 [Serializable]
 class GameData
 {
     public float experience = 0;
     public float score = 0; 
 }

MyGameScene.cs file. All other scene scripts inherit from this class as it holds general stuff about each scene.

 // default class that includes all necessary stuff about each scene in general.
 // All other scene scripts inherit from this class.
 using UnityEngine;
 using UnityEngine.UI;
 
 public class MyGameScene : MonoBehaviour 
 {
     public Button PlayBtn;
     public Button HelpBtn;
     
     protected GameObject gameStateObject;
     protected SaveLoadGameData gameState;
     
     protected void Init ()
     {
         gameStateObject = new GameObject();
         gameStateObject.name = Helper.SAVE_LOAD_GAME_DATA_GAME_OBJECT;
         SaveLoadGameData.gameState = gameStateObject.AddComponent<SaveLoadGameData>();
         SaveLoadGameData.gameState.Load();
         gameState = SaveLoadGameData.gameState;
     }
     
     // other useful functions for the scene
 }

A scene inheriting from MyGameScene:

 using UnityEngine;
 using UnityEngine.UI;
 
 public class MainMenu : MyGameScene 
 {
     public Text gameTitle;
     public Text gameSubtitle;
     
     public Button newGameBtn;
     
     void Awake ()
     {
         Init();
     }
     
     // main menu functions etc...
 }

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
1

Answer by callen · Dec 22, 2015 at 05:40 PM

There's nothing generally wrong with this pattern, and in fact I use a variant of it myself fairly often.

Something else that I like to do, but I don't know if you'll find this valuable, is to use an accessor to dynamically create my singleton like this:

 //MySingletonScript could be any singleton, in this case the SaveLoadGameData script
 public static MySingletonScript Instance 
 {
     //Now, MySingletonScript.Instance will never return null!
     get {
         if(inst == null) inst = createInstance();
         return inst; 
     }
 }

 private static MySingletonScript inst;

 private static MySingletonScript createInstance() {
     GameObject gob = new GameObject("MySingletonScript instance");
     return gob.AddComponent<MySingletonScript>();
 }

Now, since you're abstracting away this process, your Init() method would just need to call SaveLoadGameData.Instance.Load();

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

31 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 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

How do I get a U.I. image to remember if it is active or Not Active Across Scene Changes Using Arduino 2 Answers

OnDisable calls singleton instance, creates unwanted object + errors 1 Answer

Persisting data between scenes: can't find an answer 2 Answers

Saving/Loading gameobject name in .dat file 1 Answer

How easy it is to fake data stored in Application.persistentDataPath? 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