So ive created a player selection scree with 5 unlocked players that the user can choose from. I thin created one chcracter that i want to be locked. I made it a button that when clicked asks if you want to purchase player with coins… Once you buy it its unlocked. The way i did that was i made two buttons. One on top that when clicked it is now set inactive. Which reveals the second button with the players image showing which character it is. The top button is set to low opacity so you can see it clearly anyway. So now the player is showing and the top button is now gone and you see your purchased player and you can choose to play with him… Im now trying to save and re load the player though. I looked into playerprefs but that looks very hack-able… So i looked into sterilization… That looks like a a nightmare. So im wondering if anyone has any tips as to what would be the easiest way to do this. Saved purchased item state and then load it if you close the app and re load it… Thanks!
You’re going to have to pick a method. Even if it’s an online data system. There are backend services that you can use for free if you don’t plan to store a lot of data. If you don’t want to be online, you have to pick a local save method. There are ways to make playerprefs a little more secure if nothing else, but you’ll have to save it somewhere.
But if you are doing iap for the coins and that’s why you are worried, you’ll just have to consider what is the chance a player will hack to open up the one char. In all reality, you can probably get away with a local save of some sort. Even if it’s just a secure player pref. And here is a free asset that will do that Unity Asset Store - The Best Assets for Game Making
Otherwise, look into a backend service. I suggest playfab as it’s free tier will probably cover what you need.
you can always encrypt you playerPrefs data using any encryption technique you see fit and then decrypt them in game.
Serialization is dumb way easy. You just need container class where You store all data. Then You serialize just that class into file and when You need it You just deserialize it and put it into class.
Your storage class cab look like so:
public class Characters{
public static Characters current = new Characters();
bool Char1 = false;
}
Thanks to static current variable You can just type Characters.current.Char1 and set or read that variable. Add [System.serializable] at the top of this class and You have Your container for all You saved data. Just use BinaryFormatter to save Characters.current and all You data will be saved with single line.
Also thanks to that approach if You would like to expand character list You have everything in one place so adding more content will be fast and easy.
I’ve tried Using PlayerPrefs to save my character unlock system but PP wont save a GameObject. Only floats, strings, and bools. So i have a screen with 6 characters that are in side a sideways listpicker. i then have 5 default playable characters and one locked character. I have the purchase system working fine… The player purchases the gold with Real time money, they gold pack is then added to the players gold, they then go to the listpicker and choose the character for purchase, which then sets it active, or in my case i have a button over a button and when they buy it that top button goes away revealing the acual button to choose the character they just bought. My problem is, saving the damn thing… I cant seem to figure out how playerprefs would even work for this. Here is some code i used to unlock the player…
This is my PlayerManager.CS Script…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerManager : MonoBehaviour
{
public static string playerTag;
public static string playerImage;
public GameObject player1;
public GameObject player1Image;
public static bool player1Image1;
public static bool purchased;
void Start()
{
player1Image1 = player1Image;
// DontDestroyOnLoad(this);
}
void Update()
{
if (purchased == true)
{
Destroy(GameObject.FindWithTag("player1Image"));
// PlayerPrefs.SetString("player1Image", playerImage);
}
}
public void LoadPlayer1()
{
if (purchased == true)
{
player1.SetActive(true);
player1Image.SetActive(false);
PlayerPrefs.SetString("player1Image", playerImage);
} else if (purchased == false)
{
player1Image.SetActive(true);
// player1.SetActive(false);
}
}
}
This is my GameManager.CS Script… It hold all info to game like gold… So i call the buy function within game manager and it tells the playermanager script whether the purchase was successful or not…
public void BuyGuyOne()
{
if (GoldManager.gold > 100) {
GoldManager.gold -= 100;
PlayerPrefs.SetInt ("Gold", GoldManager.gold);
//PlayerPrefs.SetInt("playerOneImage", 0);
PlayerManager.purchased = true;
PlayerPrefs.Save();
confirmScreen.SetActive (false);
deniedScreen.SetActive (false);
} else {
PlayerManager.purchased = false;
confirmScreen.SetActive (false);
deniedScreen.SetActive (true);
}
}
now the guy unlocks just fine… But it doesn’t save that unlock state after i close and reopen the game… What exactly am i missing? i cant use player prefs its seems and serialized stuff just melts my brain…
Dont mind the bools and statics and stuff. I was playing around with stuff ![]()
Since you can’t save gameobjects, you have to have some way of knowing that gameobject is bought. Either a reference to that gameobject or some code. Like character 1 is ID 001, so if you have that in your playerpref, you know that character is open. Or, you can even save out a playerpref per character. So if you have a playerpref named after the character with the value “locked” or “open” then you know what to do with that character. There are a bunch of different ways to do this.
Edit: Also note there are several ways of doing this. This was just an example of maybe using playerprefs. As long as you can get the data into a string, you can save it to a playerpref.
Serialization ain’t too bad in it’s simplest form if you find a proper tutorial:
Also, using PlayerPrefs for large amount of data ain’t too good idea (not saying you are doing this), I don’t remember exact size limits, and I think it changes depending on platform… but it might be something like 1mb…
Ok here is my approach explained and coded:
First lets make a class that we will save:
using UnityEngine;
using System.Collections;
//We tell Unity that this class can be Serialized.
[System.Serializable]
//Notice that there is no MonoBehaviour. This allow us to use the class without attaching it into object in the scene.
//It also allows to use this class between scenes without loosing any data.
public class Game {
//This line allow us to just type Game.current to access variables inside class.
public static Game current = new Game();
//You probably want to save amount of gold as well.
int Gold = 0;
//This will store if character was bought;
bool CharacterPurchased = false;
}
Now our SaveLoad class:
using UnityEngine;
using System.Collections;
//This allow us to use BinaryFormatter;
using System.Runtime.Serialization.Formatters.Binary;
//This allow us to read files from device
using System.IO;
public static class SaveLoad {
public static void SaveGame(){
BinaryFormatter bf = new BinaryFormatter ();
//Check if file exist already
if(File.Exists(Application.persistentDataPath + "/SavedGame.gd")){
//Open file and overwrite whats there
FileStream file = File.Open (Application.persistentDataPath + "/SavedGame.gd", FileMode.Create);
bf.Serialize(file, Game.current);
}
else{
//If file is not there create new one and save data
FileStream file = File.Create (Application.persistentDataPath + "/SavedGame.gd");
bf.Serialize (file, Game.current);
}
file.Close ();
}
public static void LoadGame(){
//Check if file exist
if(File.Exists(Application.persistentDataPath + "/SavedGame.gd")){
BinaryFormatter bf = new BinaryFormatter ();
//Open file and cast it into variable
FileStream file = File.Open (Application.persistentDataPath + "/SavedGame.gd", FileMode.Open);
Game game = (Game)bf.Deserialize (file);
file.Close();
//Now we can set variables in our container class
Game.current.Gold = game.Gold;
Game.current.CharacterPurchased = game.CharacterPurchased;
}
else{
Debug.Log("File do not exist");
}
}
}
Because functions are static You can call them from any script. Now how to modify Your scripts to make it work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerManager : MonoBehaviour
{
public static string playerTag;
public static string playerImage;
public GameObject player1;
public GameObject player1Image;
public static bool player1Image1;
public static bool purchased;
void Start()
{
player1Image1 = player1Image;
purchased = Game.current.CharacterPurchased;
// DontDestroyOnLoad(this);
}
void Update()
{
if (purchased == true)
{
Destroy(GameObject.FindWithTag("player1Image"));
// PlayerPrefs.SetString("player1Image", playerImage);
}
}
public void LoadPlayer1()
{
if (purchased == true)
{
player1.SetActive(true);
player1Image.SetActive(false);
PlayerPrefs.SetString("player1Image", playerImage);
} else if (purchased == false)
{
player1Image.SetActive(true);
// player1.SetActive(false);
}
}
}
public void BuyGuyOne()
{
//Put Game.current.Gold into variable for easy access
if (Game.current.Gold > 100) {
Game.current.Gold -= 100;
Game.current.CharacterPurchased = true;
SaveLoad.SaveGame();
confirmScreen.SetActive (false);
deniedScreen.SetActive (false);
} else {
Game.current.CharacterPurchased = false;
confirmScreen.SetActive (false);
deniedScreen.SetActive (true);
}
}
And here You have it.
@Bantaru Yeah i picked through the script you posted and i just cant get it. Thanks for the help anyway. This is what i have so far, maybe youll see something i dont…
So when the game starts you have a panel up with 5 players that you can choose to play with… You choose a player and the game lods in the same scene… That all works fine… I have a Script called GameUI and a Singleton Script Called GameManager.
GameManager
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameManager : Singleton<GameManager>
{
public bool soundOn = true;
public bool isPause = false;
public bool isGameOver = false;
public bool isGrowable = true;
public static string playerTag;
public static string playerImage;
//Players
public GameObject player6;
public GameObject player7;
public GameObject player8;
public GameObject player9;
public GameObject player6Cover;
public GameObject player7Cover;
public static bool player1Image1;
public GameObject confirmScreen;
public GameObject deniedScreen;
//public GameObject buyScreen;
public static int gold;
public GameObject StorePanel;
// Text text;
public static int score;
public static int bestScore;
public static bool purchased;
public static bool isNotPurchased;
void Start()
{
bestScore = PlayerPrefs.GetInt("BestScore", 0);
purchased = Game.current.Player6PurchasedTrue;
isNotPurchased = Game.current.Player6PurchasedFalse;
if (Game.current.Player6PurchasedFalse)
{
purchased = false;
player6.SetActive(false);
}
}
void Update()
{
if (score == 10){
KTGameCenter.SharedCenter().SubmitAchievement(100,"000001",true);
Debug.Log("Achieved 10 Points!");
}
if (score == 30){
KTGameCenter.SharedCenter().SubmitAchievement(100,"000002",true);
Debug.Log("Achieved 30 Points!");
}
if (score == 50){
KTGameCenter.SharedCenter().SubmitAchievement(100,"000003",true);
Debug.Log("Achieved 50 Points!");
}
if (score == 100){
KTGameCenter.SharedCenter().SubmitAchievement(100,"000004",true);
Debug.Log("Achieved 100 Points!");
}
if (score == 150){
KTGameCenter.SharedCenter().SubmitAchievement(100,"000005",true);
Debug.Log("Achieved 150 Points!");
}
}
public void Player6()
{
//Put Game.current.Gold into variable for easy access
if (Game.current.Gold > 100)
{
Game.current.Gold -= 100;
purchased = true;
player6.SetActive(true);
Destroy(GameObject.FindWithTag("player1Cover"));
SaveLoad.SaveGame();
}
else
{
purchased = false;
//confirmScreen.SetActive(false);
deniedScreen.SetActive(true);
}
}
public void Player7()
{
}
public void Player8()
{
}
public void Player9()
{
}
public void Restart()
{
isGameOver = false;
isGrowable = false;
score = 0;
SoundManager.GetInstance().MakeClickSound();
SceneManager.LoadScene("Game");
}
public void IsScalable()
{
isGrowable = true;
}
public void Pause()
{
isPause = true;
Time.timeScale = 0f;
SoundManager.GetInstance().MakeClickSound();
}
public void Resume()
{
//selector.SetActive(true);
isPause = false;
Time.timeScale = 1f;
SoundManager.GetInstance().MakeClickSound();
}
public void Quit()
{
//selector.SetActive(false);
isPause = false;
isGameOver = false;
score = 0;
Time.timeScale = 1f;
SoundManager.GetInstance().MakeClickSound();
SceneManager.LoadScene("Title");
SaveLoad.SaveGame();
}
public void GameOver()
{
// SaveLoad.SaveGame();
isGameOver = true;
SaveData();
SoundManager.GetInstance().MakeGameOverSound();
}
public void titleEnter()
{
//appears after menu screen
//selector.SetActive(true);
}
public void willGrow()
{
isGameOver = false;
isGrowable = true;
isPause = false;
Time.timeScale = 1f;
SoundManager.GetInstance().MakeClickSound();
}
void SaveData()
{
if ( score > bestScore)
{
SaveLoad.SaveGame();
bestScore = score;
PlayerPrefs.SetInt("BestScore", bestScore);
}
}
public void Score()
{
score += 1;
}
public void Buy100Gold()
{
Purchaser.Instance.Buy100Gold();
}
public void Buy400Gold()
{
Purchaser.Instance.Buy400Gold();
}
public void Buy750Gold()
{
Purchaser.Instance.Buy750Gold();
}
public void Buy1000Gold()
{
Purchaser.Instance.Buy1000Gold();
}
public void Store()
{
isGrowable = false;
isPause = true;
Time.timeScale = 0f;
SoundManager.GetInstance().MakeClickSound();
StorePanel.SetActive(true);
}
public void Closestore()
{
isPause = false;
Time.timeScale = 1f;
SoundManager.GetInstance().MakeClickSound();
StorePanel.SetActive(false);
//GameOver.SetActive(false);
isGrowable = false;
}
public void CloseConfirmScreen()
{
confirmScreen.SetActive(false);
}
public void OpemConfirmScreen()
{
confirmScreen.SetActive(true);
}
public void CloseDenyScreen()
{
deniedScreen.SetActive(false);
}
public void CloseDenyAndStore()
{
deniedScreen.SetActive(false);
}
}
Then this is my GameUI…
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using ChartboostSDK;
using UnityEngine.SceneManagement;
public class GameUI : MonoBehaviour
{
public GameObject gameOverPanel;
// These are buttons to start and exit game.
public Button playButton;
public Button homeButton;
//public Button menuButton;
//Buying Gold Buttons
public Button Buy50Gold;
public Button Buy100Gold;
public Button Buy500Gold;
//Enabling and Disabling Screens
public Button openConfirmScreen;
public Button closeDenyScreen;
public Button denyAndStoreScreen;
public Button closeConfirmScreen;
public Button closeStore;
public Button openStore;
// These are text holders for score/gold/and best score.
public Text scoreText;
public Text resultScore;
public Text resultBestScore;
public Text goldText;
void Awake()
{
SaveLoad.LoadGame();
}
void Start()
{
// SaveLoad.LoadGame();
gameOverPanel.SetActive(false);
SetupButton();
HomeButton();
StoreButton();
ConfirmOpen();
DenyClose();
DenyStoreScreen();
CloseConfirm();
CloseStore();
scoreText.text = "" + GameManager.score;
goldText.text = "" + Game.current.Gold;
}
void Update()
{
SetScoreText(GameManager.score);
SetGoldText (Game.current.Gold);
}
public void SetScoreText(int score)
{
scoreText.text = "" + score;
}
public void SetGoldText(int Gold)
{
goldText.text = "" + Game.current.Gold;
}
void StoreButton()
{
openStore.onClick.AddListener(Store);
}
void SetupButton()
{
playButton.onClick.AddListener(Restart);
}
void HomeButton()
{
homeButton.onClick.AddListener(Quit);
}
void ConfirmOpen()
{
openConfirmScreen.onClick.AddListener(OpenConfirm);
}
void DenyClose()
{
closeDenyScreen.onClick.AddListener(CloseDenyScreen);
}
void DenyStoreScreen()
{
denyAndStoreScreen.onClick.AddListener(CloseDenyScreenOpenStore);
}
void CloseConfirm()
{
closeConfirmScreen.onClick.AddListener(CloseConfirmScreen);
}
void CloseStore()
{
closeStore.onClick.AddListener(Restart);
}
public void Restart()
{
SoundManager.GetInstance().MakeClickSound();
GameManager.GetInstance().Restart();
}
public void Quit()
{
SoundManager.GetInstance().MakeClickSound();
GameManager.GetInstance().Quit();
// Show interstitial at location HomeScreen.
// See Chartboost.cs for available location options.
Chartboost.showInterstitial(CBLocation.LevelComplete);
SaveLoad.SaveGame();
}
public void GameOver()
{
gameOverPanel.SetActive(true);
resultScore.text = "" + GameManager.score;
resultBestScore.text = "" + GameManager.bestScore;
goldText.text = "" + Game.current.Gold;
KTGameCenter.SharedCenter().SubmitScore(GameManager.score,"8052013");
SaveLoad.SaveGame();
// ... do this.
// Show interstitial at location GameScreen.
// See Chartboost.cs for available location options.
Chartboost.showInterstitial(CBLocation.Default);
}
public void OpenConfirm()
{
GameManager.GetInstance().OpemConfirmScreen();
}
public void CloseConfirmScreen()
{
GameManager.GetInstance().CloseConfirmScreen();
}
public void CloseDenyScreen()
{
GameManager.GetInstance().CloseDenyScreen();
}
public void CloseDenyScreenOpenStore()
{
GameManager.GetInstance().CloseDenyAndStore();
}
public void Store()
{
GameManager.GetInstance().Store();
}
}
Now most of this has nothing to do with the player purchase screen. So i tried two different ways to be able to buy the player. First i added another panel inside the main canvas and set it to active when you pressed the shop button. Then i tried to create another scene that opened the shop and you can browse gold and purchasable players. I am able to buy the players and the gold is subtracted from your total gold amount, but getting the player unlocked is the problem. I then made a button and an image within the player selection screen within the game to represent player 1 that you can buy. The image is a faded out version that says not purchased yet. and the other is the actual button that you press to play with that guy. When you start the game i had the image set to active until you bought the player inside the shop. So all you seen was the faded guy that says he isnt purchased. Then when you go into the shop and buy him the image is no longer there and the button that shows the player is now there. The problem im facing is that i cant get the button to show when i quit the game and open it back up…
This is the shopui script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShopUI : MonoBehaviour {
//Buy Player Buttons
public Button buyPlayer1;
public Button buyPlayer2;
public Button buyPlayer3;
public Button buyPlayer4;
//Buying Gold Buttons
public Button BuyButton;
public Button Buy100Gold;
public Button Buy400Gold;
public Button Buy750Gold;
public Button Buy1000Gold;
public Button closeStore;
public Text goldText;
//public GameObject StorePanel;
void Start ()
{
//Onclick Listseners For Buying Players.
buyPlayer1.onClick.AddListener(BuyPlayer1);
buyPlayer1.onClick.AddListener(BuyPlayer2);
buyPlayer1.onClick.AddListener(BuyPlayer3);
buyPlayer1.onClick.AddListener(BuyPlayer4);
//Onclick Listeners for buying gold.
Buy100Gold.onClick.AddListener(OneHundredGold);
Buy400Gold.onClick.AddListener(FourHundredGold);
Buy750Gold.onClick.AddListener(SevenFiftyGold);
Buy1000Gold.onClick.AddListener(ThousandGold);
StoreButton();
goldText.text = "" + Game.current.Gold;
// StoreButton();
}
void Update ()
{
SetGoldText(Game.current.Gold);
}
void StoreButton()
{
closeStore.onClick.AddListener(Store);
}
public void SetGoldText(int Gold)
{
goldText.text = "" + Game.current.Gold;
}
public void Store()
{
GameManager.GetInstance().Closestore();
SaveLoad.SaveGame();
}
public void OneHundredGold()
{
GameManager.GetInstance().Buy100Gold();
}
public void FourHundredGold()
{
GameManager.GetInstance().Buy400Gold();
}
public void SevenFiftyGold()
{
GameManager.GetInstance().Buy750Gold();
}
public void ThousandGold()
{
GameManager.GetInstance().Buy1000Gold();
}
public void BuyPlayer1()
{
GameManager.GetInstance().Player6(); // This is where the buy player is called//
}
public void BuyPlayer2()
{
GameManager.GetInstance().Player7();
}
public void BuyPlayer3()
{
GameManager.GetInstance().Player8();
}
public void BuyPlayer4()
{
GameManager.GetInstance().Player9();
}
}
The above code is shown where is says BuyPlayer1… That calls the gamemanager script to buy the player…
[code=CSharp]public void Player6()
{
//Put Game.current.Gold into variable for easy access
if (Game.current.Gold > 100)
{
Game.current.Gold -= 100;
purchased = true;
player6.SetActive(true);
Destroy(GameObject.FindWithTag("player1Cover"));
SaveLoad.SaveGame();
}
else
{
purchased = false;
//confirmScreen.SetActive(false);
deniedScreen.SetActive(true);
}
}
[/code]
as you can see i say if you got enough gold then buy the player… then it calls for purchased to be true and to set the image that says not purchased yet to be false so it doesnt show. Then i destroy it. then the game is saved. So then i close out the shop and the game is shown and now the player can be selected. Then i close the game anc come back and it shows the image still there and i have to buy him again… Like i said most of this code is messed up cause ive been messing with it for the past two das tring every which way i can to figure it out. Im not sure what purchased is refering to within you Game script you posted and i thin thats not even being called properly. But the setting the image to not active should of gotten rid of the image and destroying it should of also, and by saving it should of loaded the game the same way it was saved, unless theres somehting im missing within the SaveLoad script ?? Anything helps. Thanks… Oh and sorry for the long post.
Yeah, so the problem i think im having is its not saving GameObjects. After player is bought the cover image is set to inactive and should save that way but it isnt. I reload the game and the cover image that says please purchase is showing again which makes me go buy the guy again. Do i have to reference the players cover in the SaveLoad script? or the Game Script?
SaveLoad script stores bool that sets purchased to true if player bought a skin. So Your logic after if(purchased) must have error somewhere.
The issue is I think because I’m trying to save the actual game object opposed to the if purchased variable. I found that game objects can’t be deserialized. They can how ever be saved as an xml file. So I re did the save load script and tried to save it as that but somewhere I messed that up too cause it was loading the game as it was saved without placing load within any script. So I think what I’m going to do is redo the scripts and try it as you suggested. So I’m declaring that if the player was purchased it will equal true? Then set it as save after the function calls true? I’m just trying to make sure I understand the functionality of your script.
My logic after the if(purchased) variable is this
public GameObject player1;
public void PurchasePlayerOne()
{
If (Game.current.Gold >= 99)
{
Purchased();
}else
{
NotPurchased();
}
}
// The above code I've called that if you have more than 99 gold then call this function.
public void Purchased()
{
Game.current.Purchased = true;
Game.current.Gold -= 100;
Player1.SetActive(true);
SaveLoad.SaveGame();
}
//Else if you don't have enough gold call this function.
public void NotPurchased()
{
Game.current.Purchased = false;
Player1.SetActive(false);
SaveLoad.SaveGame();
}
I feel like somewhere in here I'm missing something..