- Home /
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
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
@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 { }
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
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.
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
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
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
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
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;
}