简体   繁体   中英

Unity - C# : how can I use a value in different scenes?

I have made my first Unity3D game. It's a racing game with the infinite road. I made some pickup coins too. the problem is when I pick up the coins and then I go to shop menu to see whether it's added to the total coins or not, it is not added till I play another round and then the coins i collected the round before will be added. It's like a delay or something.

Is it because I don't know how can I use a value in different scenes? or it,s something else. someone told me to use PlayerPrefs, I used it in my scripts but for this, I mean the count of coins, I don't know how to use it.

The script bellow is my player script in which I count the pickup coins and some other things related to the player. I only bring the Ontrigger and count related codes.

void Start () {
    CameraAnimation = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Animator>();
    _GameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
    _AudioSource = GetComponent<AudioSource>();
    count = 0;
    SetCountText ();
}

void OnTriggerEnter(Collider other){
       if(other.gameObject.tag == "Coins") {
             count = count + 1;
             SetCountText ();
        }
}

public void SetCountText(){
    CountText.text = count.ToString ();
}

The code below is my calculateCoin in which I add a count of collected coins to the previous value and show the total in shop scene textbox:

public class CalculateCoin : MonoBehaviour{

    // Use this for initialization
    public static int Coin = 10000;
    public Text ShowCoin;
    void Start () {
        ShowCoin.text = PlayerPrefs.GetInt("Coin").ToString();
        Coin =PlayerPrefs.GetInt("Coin")+Player.count;
        PlayerPrefs.SetInt ("Coin", Coin);
  }
}

First Option, You can add 'DontDestroyOnLoad' for specific GameObject that include data as container. so It could be used as shared data between scene.

or Make 'Singleton' class and use it as data container it might be option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM