Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
2
Question by Ashmit2020 · Jan 22, 2021 at 08:32 AM · uisavingbinaryformatterbinarywriter

How to save a ui button for binary formatter

I am trying to make a way from which I can save my player's purchase in my shop system through binary files but the problem is it only supports int float string values I want to save a purchase. In my shop when player buys something buy button changes to equip button but it resets when player enter different scene or leave the game. I think custom classes are used for this process but how can I do that in the script please help. Thanks

Comment
Add comment · Show 16
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 Llama_w_2Ls · Jan 22, 2021 at 09:05 AM 0
Share

You have to save the state of objects in your scene, either through floats, ints, bools or strings. For example, if you wanted to save your player's spawnpoint, you wouldn't save and load the entire gameobject, you would only save their position, and interpret that when loading, to place the player in that position. The same with UI buttons:


You could save a string that keeps the state of the button (if buy button or equip button). Then, when loading your data, you check the state that was loaded, and if the state was "BUY", set the button to Buy state. Else, set it to Equip state. @Ashmit2020

avatar image Ashmit2020 Llama_w_2Ls · Jan 22, 2021 at 09:58 AM 0
Share

@Llama_w_2Ls thanks for the help but I am not quite understanding it. I mean I understood it a bit theoretically but still don't know how to write that code that you guided me to do so can you please give me a sample that how can I check about buy and equip button state I mean I know how to do that using if statements but using it for binary is still a bit unclear. What I planned to do is to create a script playerdata and another script where I will make a binary formatter and the save it from there. I will follow brackeys video for the binary transformer part hope that will work for me but for the part where I declare what to store please help me. Here is the playerdata script it is empty: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Scene$$anonymous$$anagement; public class PlayerData : $$anonymous$$onoBehaviour { }

avatar image Llama_w_2Ls Ashmit2020 · Jan 22, 2021 at 10:10 AM 0
Share

You would save a string in the player data called:

 public string ButtonState;

Then, when saving your playerData, you would write:

 if (EquipButton)
     ButtonState = "Equip";
 else
     ButtonState = "Buy";

Finally, when loading your data, you would write:

 string state = ButtonState;
 
 if (ButtonState == "Buy")
     $$anonymous$$yButton = BuyButton;
 else
     $$anonymous$$yButton = EquipButton;

Something along these lines. Hope you find this of use. @Ashmit2020

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Llama_w_2Ls · Jan 24, 2021 at 02:18 PM

Saving a button using a file

Note: I'm posting a new answer to completely clarify everything to do with what my answer to the question was_


Description

The only thing you can write to a text file is text. So how can we save a UI element? Well, we can save the state of the button as a string, and interpret that state OnLoad, in order to load the correct button, that was saved.


For example: If we had two types of buttons: 'Buy' and 'Equip', when we are saving our button, we check whether the button is of type 'Buy', or of type 'Equip'. We can save that as a string. Then, when we load our scene, we check the save file for the save state. If the text reads 'Buy', we set the button to a buy button, else if it says 'Equip', we set it to an Equip button. Simple as that.


Example

I re-created a practical example of saving a UI button in the Unity Editor:


Scene View

The scene is comprised of a Main Camera, a canvas with 4 buttons on, and an empty GO, called 'SceneSaver', which has a script on called 'SaveEverything'.


Two of the buttons are the types of buttons you could have in a scene, the Buy and Equip buttons. One of the buttons is called 'MyButton', and is the Button we want to save and load. It has a script on called 'LoadEverything'. The final button is called 'SaveButton' and OnClick, runs a public method called Save() from the SaveEverything script.

Hierarchy

Game View


Scripts

This is the 'SaveEverything' script:

 using UnityEngine;
 using System.IO;
 
 public class SaveEverything : MonoBehaviour
 {
     // What script to save
     public LoadEverything MyButton;
 
     public void Save()
     {
         // What data to save
         string saveData = MyButton.state.ToString();
 
         // Where the data is stored
         string path = Application.persistentDataPath + "\\buttonstate.save";
 
         // Writes data to file
         if (File.Exists(path))
         {
             File.WriteAllText(path, saveData);
         }
         else
         {
             File.Create(path).Close();
             File.WriteAllText(path, saveData);
         }
     }
 }
 
 public enum ButtonState
 {
     Buy,
     Equip
 }

 

This is the 'LoadEverything' script:

 using UnityEngine;
 using UnityEngine.UI;
 using System.IO;
 using System;
 
 public class LoadEverything : MonoBehaviour
 {
     // Types of buttons
     public GameObject BuyButton;
     public GameObject EquipButton;
 
     public ButtonState state;
 
     void Start()
     {
         // What file to read save data from
         string path = Application.persistentDataPath + "\\buttonstate.save";
 
         // Get data and set state to that data
         if (File.Exists(path))
         {
             string data = File.ReadAllText(path);
             
             if (Enum.TryParse(data, out ButtonState State))
                 state = State;
         }
 
         // Copy button properties onto this button
         // depending on the state
         switch (state)
         {
             case ButtonState.Buy:
                 SetButton(BuyButton);
                 break;
             case ButtonState.Equip:
                 SetButton(EquipButton);
                 break;
         }
     }
 
     void SetButton(GameObject button)
     {
         // Set on-click method of button
         Button myButton = GetComponent<Button>();
         Button targetButton = button.GetComponent<Button>();
 
         myButton.onClick = targetButton.onClick;
 
         // Set text of button
         Text myText = GetComponentInChildren<Text>();
         Text targetText = button.GetComponentInChildren<Text>();
 
         myText.text = targetText.text;
     }
 }



If anything is unclear, let me know. If it doesn't work, let me know. I tested this and it works, so I will help you to re-create my scene. @Ashmit2020


gameview.png (7.1 kB)
hierarchy.png (14.7 kB)
Comment
Add comment · Show 30 · 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 Ashmit2020 · Jan 25, 2021 at 06:29 AM 0
Share

OK I need help . I implemented it and here is what I did. I made a gameobject called scenesaver and added saveeverything in it and added a onclick save() function in back button. I have equip button and a save button the method that controls them is in shop script and when a purchase went successfully this thing runs Buybutton.SetActive(false) and Equipbutton.SetActive(true) and other stuff for the purchase. I referenced buybutton in BuyButton slot and equipbutton in EquipButton slot I dont have any specific $$anonymous$$yButton so I used buybutton for it as well thinking that if the buybutton is not active it will save it as BuyButton.SetAvctive(false) but it is still not saving and the ButtonState is also not changing. So what might be the problem? If you need any more information about the problem I can give that.@Llama_w_2Ls

avatar image Llama_w_2Ls Ashmit2020 · Jan 25, 2021 at 08:54 AM 0
Share

Can you send screenshots of your setup in the scene? Also, are you getting any errors in the console whatsoever. You might not have assigned something to one of the scripts.


Finally, what did you attach the 'LoadEverything' script to? It should be attached to the button you want to save, and reference that button to the 'SaveEverything' script, in the slot called $$anonymous$$yButton. @Ashmit2020

avatar image Ashmit2020 Llama_w_2Ls · Jan 25, 2021 at 09:39 AM 0
Share

Yes I am getting an error now this is it NullReferenceException: Object reference not set to an instance of an object LoadEveryThing.SetButton (UnityEngine.GameObject button) (at Assets/LoadEveryThing.cs:53) LoadEveryThing.Start () (at Assets/LoadEveryThing.cs:33) It is on line 53 that is myText.text = targetText.text; This seems odd cuz I have filled every slot. Here are the screenshots. I am considering this back button as save button ![Save Button][1] I am considering Buy button as $$anonymous$$y button because I want to save it when it is BuyButton.SetActive(false) means when it is disabled. ![$$anonymous$$y Button][2] @Llama_w_2Ls

Show more comments
avatar image
0

Answer by CmdrZin · Jan 23, 2021 at 07:13 AM

Here's what I use to save data. Just serialize a class with all the stuff to save.

 This code is in the script's class.
     // *** SAVE/LOAD Game Operations ***
     public void Save()
     {
         BinaryFormatter bf = new BinaryFormatter();
 
         // Save High score.
         file = File.Open(Application.persistentDataPath + "/scoreInfo.dat", FileMode.OpenOrCreate);
         ScoreData sdata = new ScoreData();
 
         sdata.bestStarDate = bestStarDate;
         sdata.bestCredits = bestCredits;
 
         bf.Serialize(file, sdata);
         file.Close();
     }
 
     public void LoadHiScore()
     {
         // Get Hi-Score data
         if (File.Exists(Application.persistentDataPath + "/scoreInfo.dat"))
         {
             BinaryFormatter bf = new BinaryFormatter();
             FileStream file = File.Open(Application.persistentDataPath + "/scoreInfo.dat", FileMode.Open);
             // cast binary data to ScoreData class struct.
             ScoreData data = (ScoreData)bf.Deserialize(file);
 
             bestStarDate = data.bestStarDate;
             bestCredits = data.bestCredits;
 
             file.Close();
         }
     }
 
 [Serializable]
 public class ScoreData
 {
     public float bestStarDate;
     public float bestCredits;
 }
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

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

Problem with my binary files 1 Answer

Should I avoid using BinaryFormatter altogether? 3 Answers

Initialize List in User Data Class without deleting binary file 0 Answers

Is this code handling fall back on previous saves upon failure the right way? 2 Answers

IOException: Sharing violation on path 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