im making a platformer in Unity and i just added a score and coin function but everytime player goes to the next level the coin amount that the player collected resets I dont know why and I cant seem to find out why. Here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class CoinPicker : MonoBehaviour
{
private float Coins = 0;
public TextMeshProUGUI textcoins;
private void OnTriggerEnter2D(Collider2D other) {
if (other.transform.tag == "Coins") {
Coins ++;
textcoins.text = Coins.ToString();
Destroy(other.gameObject);
}
}
}
To save a value to be accessed across all scenes, you can use PlayerPrefs. (although I recommend upgrading to something more secure later on) Here is your script updated to use PlayerPrefs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class CoinPicker : MonoBehaviour
{
public TextMeshProUGUI textcoins;
private void OnTriggerEnter2D(Collider2D other) {
if (other.transform.tag == "Coins") {
if (PlayerPrefs.HasKey("Coins"))
{
PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + 1);
}
else
{
PlayerPrefs.SetInt("Coins", 1);
}
PlayerPrefs.Save();
textcoins.text = PlayerPrefs.GetInt("Coins").ToString();
Destroy(other.gameObject);
}
}
}
This code will check if the PlayerPref “Coins” has a value. If not, set it to 1. If so, add one to the value. The value of coins will persist across all scenes.