I'm creating a game that has multiple levels. The first three levels are free but the others can be unlocked either using coins (collected during the game) or through IAP. For the coins, I'm using a binary formatter to store the number of coins. The reason I'm using BF is because it persits through all levels(so far this seems to work as the coin score is carried through to other levels). Here is code I have so far in the coinSystem:
public class CoinSystem : MonoBehaviour
{
public TextMeshProUGUI coinScoreText;
public int coinScore;
void Start()
{
LoadScore();
}
public void Save()
{
coinScore++;
coinScoreText.text = coinScore.ToString();
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/TotalCoinScore.dat", FileMode.Create);
CoinContainer coinContainer = new CoinContainer();
coinContainer.coinScore = coinScore;
bf.Serialize(file, coinContainer);
file.Close();
}
public void LoadScore()
{
if (File.Exists(Application.persistentDataPath + "/TotalCoinScore.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/TotalCoinScore.dat", FileMode.Open);
CoinContainer coinContainer = (CoinContainer)bf.Deserialize(file);
file.Close();
coinScore = coinContainer.coinScore;
coinScoreText.text = coinScore.ToString();
}
}
}
[Serializable]
public class CoinContainer
{
public int coinScore;
}
This is code that I use to add to the coinScore.
public class Player : MonoBehaviour
{
Rigidbody rb;
public CoinSystem cs;
public bool dead = true;
void Start()
{
rb = GetComponent<Rigidbody>();
}
.
.
.
.
void OnTriggerEnter(Collider col)
{
if (!dead && col.gameObject.tag == "Enemy")
{
die();
}
if (!dead && col.gameObject.tag == "Coin")
{
cs.Save();
}
}
So now in the level select menu, I want to add a button that once clicked should enable the user to unlock a particluar level if he has enough coins. For example, if a level requires 500 coins and the user has 600, then on clicking this button the level is unlocked and the total coins now available are 100. And if the number of coins are less than what is required to unlock a level then the user should not be able to unlock that level. I'm not sure how to implement this.