- Home /
Coin System with PlayerPrefs
I was working on a basic coins system you collect coins in the game scene and you can see them on the top of the screen and when you die the amount of coins you collect will show up in the GameOver screen but there is a problem when the player picks up 1 coin it works fine but when player collects 2 or more coin it just stays on 1 the amount does not increases
Coin script(on the coin gameobjects)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Coin : MonoBehaviour { public int Coins;
private void OnCollisionEnter2D(Collision2D col) { if(col.gameObject.tag == "Player") { Coins += 1; PlayerPrefs.SetInt("CoinValue", Coins);
Destroy(gameObject); } } }
CoinScript(on the UI element in the game scene)
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class CoinScript : MonoBehaviour { public static int CoinValue; Text Coins;
// Start is called before the first frame update
void Start()
{
Coins = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
CoinValue = PlayerPrefs.GetInt("CoinValue");
Coins.text = "Coins: " + CoinValue;
}
}
CoinStorage Script(on the coin counter in the game over scene)
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class CoinStorage : MonoBehaviour { private int AllCoins; Text FinaleCoins;
// Start is called before the first frame update
void Start()
{
FinaleCoins = GetComponent<Text>();
AllCoins = PlayerPrefs.GetInt("CoinValue");
}
// Update is called once per frame
void Update()
{
FinaleCoins.text = "Coins: " + AllCoins;
}
}
I'm using playerprefs because I think I will use that coin value in a shop or something
Answer by toficofi · Aug 17, 2021 at 09:16 PM
Hi! It looks like in your Coin script, you forgot to set the "Coins" variable from PlayerPrefs, so it's always set to 0. Try adding this in your Coin script:
void Start()
{
Coins = PlayerPrefs.GetInt("CoinValue");
}
Oh thank you very much. everytime I try to write some code I always make some small mistakes then nothing works properly and finding these mistakes can be really hard sometimes