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 G3R1 · Jun 27, 2017 at 02:14 PM · variablesaveloadintbinary

Checking if int is !null not working ? Strange...

Hi,

So I was just testing binary save and load in Unity when i encountered this problem. I am trying to save "coins" variable but in the beginning the number of coins is zero or null and i tried to put a condition "if coins != null { LoadPlayerProgress(); } else { coins = 5; SavePlayerProgress;}". The thing is that when i run the game on the editor the ui text where I display coins shows zero coins and not five. Here I am pasting the codes so you can check it by yourself because its really simple but it just doesn't work properly.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System;
 using System.Runtime.Serialization.Formatters.Binary;
 using System.IO;
 
 public class SaveLoad : MonoBehaviour {
 
     public static SaveLoad instance;
 
     void Awake()
     {
         if (instance == null) {
             DontDestroyOnLoad (gameObject);
             instance = this;
         } 
         else if(instance != this)
         {
             Destroy (gameObject);
         }
     }
 
     public void Save()
     {
         BinaryFormatter bf = new BinaryFormatter ();
         FileStream file = File.Create (Application.persistentDataPath + "/playInfo.sav");
 
         PlayerData data = new PlayerData ();
         data.coins = SaveLoad.instance.GetComponent<ButtonControl>().coins;
 
         bf.Serialize (file, data);
         file.Close ();
     }
 
     public void Load()
     {
         if (File.Exists (Application.persistentDataPath + "/playInfo.sav"))
         {
             BinaryFormatter bf = new BinaryFormatter ();
             FileStream file = File.Open (Application.persistentDataPath + "/playInfo.sav", FileMode.Open);
             PlayerData data = (PlayerData)bf.Deserialize (file);
             file.Close ();
 
             SaveLoad.instance.GetComponent<ButtonControl>().coins = data.coins;
         }
     }
 
     [Serializable]
     class PlayerData
     {
         public int coins;
     }
 }
 

Here is the other script that contains a function for adding coins using a button. In the editor i have also added two other buttons to save and load the progress.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class ButtonControl : MonoBehaviour {
 
     [HideInInspector]
     public int coins;
     public Text text;
 
     // Use this for initialization
     void Start () 
     {
         if (coins != null)
         {
             SaveLoad.instance.Load ();
 
         } 
         else
         {
             coins = 5;
             SaveLoad.instance.Save ();
         }
     }
     
     // Update is called once per frame
     void Update () {
         text.text = coins.ToString ();
     }
 
     public void AddCoins()
     {
         coins += 100;
     }
 }
 

Also, I erased the saved data in the persistent path where unity store the savings and still coins text shows zero coins and not 5.

If I use a nullable int "int? coins;" and put the same condition, coins text does show 5 coins and not zero but there is another problem because when I add some coins and click save and after this I exit the game and then run it again the save doesn't load and still shows 5 coins. You should also create three buttons where one of them should contain the AddCoins() function and the other two the save and load from SaveLoad class. This is strange. It is better to test this problem with my codes by yourself and see where the problem is.

Thank you, Gerald.

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 ShadyProductions · Jun 27, 2017 at 04:52 PM

int cannot contain null unless it's a nullable, you can use some nifty generic method to check if it contains the default value like so if its not a nullable int:

 public static class TypeHelper
 {
     public static bool IsDefault<T>(this T val)
     {
          return EqualityComparer<T>.Default.Equals(val,default(T));
     }
 }

Now you can use it as follows:

 int abc = 5;
 if (abc.IsDefault())
Comment
Add comment · Show 4 · 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 G3R1 · Jun 27, 2017 at 05:36 PM 0
Share

Thank's. I will try your code as soon as I can. ;)

avatar image Bunny83 · Jun 27, 2017 at 08:17 PM 0
Share

That's just a complicated way of doing:

 if (coins == 0)

default(int) is simply 0.

ps: you have a typo in your method. You named your parameter "val" but you used "obj" in your code which is not defined. Also you didn't declare you method as extension method, so you can't use it the way you did. You have to use the "this" modifier on the first parameter to turn your method into an extension method.

avatar image G3R1 Bunny83 · Jun 28, 2017 at 07:58 AM 0
Share

I also tried "if (coins == 0) { coins = 5; Save(); } else { Load() }", and this condition worked but when I added some other coins and saved the game through the function save and I quit the game on the editor and then run the game again, the coins where again 5 and not like the last save which was more than 5 coins. Anyway, I have no idea why this happens. :P

avatar image ShadyProductions Bunny83 · Jun 28, 2017 at 08:24 AM 0
Share

Yes but this works on keyvaluepairs and other types aswel which does make it useable :) $$anonymous$$y bad for the missing code, I was in a hurry. Corrected it

avatar image
0

Answer by Orami · Jun 27, 2017 at 04:36 PM

Start is called only when the prefab or object is made.

I am assuming both of these scripts are on a prefab of some sort.

If your prefab has a coin value that is anything other than 0 it will load from a file

If it is 0 you will set coins to 5 and save that to a file.

What are you trying to do exactly?

You never save after start so when you add coins it will never save. Try saving in your add coin function after you add the coins.

Comment
Add comment · Show 3 · 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 G3R1 · Jun 27, 2017 at 05:48 PM 0
Share

I have put these scripts on Camera object just for testing because my game is a lot more complex than these two scripts but the idea is the same. I am just trying to put a condition before the game save loads from the binary file that if coins variable is null which means that if the game hasn't been played or is being played for the first time, then coins = 5, else load the game save,. Now the problem is that when the game hasn't been played and I open it for the first time the coins is still zero and not five and after I add some coins with that function using a button, the coins add as they should and after I hit the save button to save the coins and then exit on the editor, and then play again, the coins are still zero...You can try it by yourself.

avatar image Orami G3R1 · Jun 27, 2017 at 07:32 PM 0
Share

But you don't change the right variable if you want to change the PlayerData class you need to change it there not a local variable called coins.

avatar image G3R1 Orami · Jun 27, 2017 at 08:06 PM 0
Share

$$anonymous$$aybe I am a little bit confused but I solved the problem I had with my current game. I am leaving this post open just in case if I encounter any problem later again. Thank's for your support Orami. ;)

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

70 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 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Delete a serialized binary save file 2 Answers

from bool array to binary file? 1 Answer

Saving/Loading variables 1 Answer

Binary Formatting Loading Error 0 Answers

Set int to object from list? 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