Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

adding coins and Ui Scores

Discussion in 'Getting Started' started by Yegor42069, Mar 20, 2023.

  1. Yegor42069

    Yegor42069

    Joined:
    Dec 5, 2022
    Posts:
    26
    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
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using TMPro;
    5.  
    6. public class CoinPicker : MonoBehaviour
    7. {
    8.     private float Coins = 0;
    9.     public TextMeshProUGUI textcoins;
    10.  
    11.     private void OnTriggerEnter2D(Collider2D other) {
    12.         if (other.transform.tag == "Coins") {
    13.             Coins ++;
    14.             textcoins.text = Coins.ToString();
    15.  
    16.  
    17.             Destroy(other.gameObject);
    18.         }
    19.     }
    20.  
    21. }  
    22.  
     
  2. Deleted User

    Deleted User

    Guest

    Is your next level a new scene?
     
  3. Yegor42069

    Yegor42069

    Joined:
    Dec 5, 2022
    Posts:
    26
    yes
     
  4. Yegor42069

    Yegor42069

    Joined:
    Dec 5, 2022
    Posts:
    26
    does it need to be something different
     
  5. CoolBeanz7

    CoolBeanz7

    Joined:
    Mar 14, 2022
    Posts:
    18
    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:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using TMPro;
    5. public class CoinPicker : MonoBehaviour
    6. {
    7.     public TextMeshProUGUI textcoins;
    8.     private void OnTriggerEnter2D(Collider2D other) {
    9.         if (other.transform.tag == "Coins") {
    10.             if (PlayerPrefs.HasKey("Coins"))
    11.             {
    12.                 PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + 1);
    13.             }
    14.             else
    15.             {
    16.                 PlayerPrefs.SetInt("Coins", 1);
    17.             }
    18.             PlayerPrefs.Save();
    19.             textcoins.text = PlayerPrefs.GetInt("Coins").ToString();
    20.             Destroy(other.gameObject);
    21.         }
    22.     }
    23. }
    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.
     
    Last edited: Apr 12, 2023