I'm trying to create a shop in another scene. You can access it anytime while playing by pressing H. My problem is that the coins that the player has collected doesn't get saved. I've been trying to search for answers but nothing seems to help.
The Codes: My Global Code that I use to save varibles:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Global : MonoBehaviour
{
public static Global Instance;
public int sumCoins;
void Awake(){
if (Instance == null){
DontDestroyOnLoad(gameObject);
Instance = this;
} else if (Instance != this){
Destroy(gameObject);
}
}
}
The code I use to buy items:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Shop : MonoBehaviour
{
public Button milk;
void Start()
{
Debug.Log("you have " + Global.Instance.sumCoins);
milk.onClick.AddListener(AddMilk);
}
void AddMilk(){
Debug.Log("You bought milk");
//if player has more than 5 coins.
//add milk
//else if player has less than 5 coins
//display "You cant buy this"
//else if player doesnt have a slot available
//display "You cant buy this"
}
}
The code that's used for counting and adding coins:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Coinsystem : MonoBehaviour
{
public int sumCoins = 0;
private int addedCoins;
int coins;
Text txt;
public GameObject count;
public void Start(){
Debug.Log("coin system working");
txt = count.GetComponent<Text>();
txt.text = "" + sumCoins;
sumCoins = Global.Instance.sumCoins;
}
public void Update(){
txt.text = "" + sumCoins;
}
public void AddCoins(int addedCoins){
sumCoins += addedCoins;
Debug.Log("Coins Added!");
}
public void SaveMoney(){
Global.Instance.sumCoins = sumCoins;
}
}
Thank you for taking your time to read this!