Access variable from a different scene in Unity

前端 未结 3 727
时光取名叫无心
时光取名叫无心 2021-01-21 20:21

I am fairly new to Unity and C# and am having some trouble. I am designing a 2d game, which has multiple levels. Each level contains a LevelManager which stores whether the leve

3条回答
  •  梦毁少年i
    2021-01-21 21:02

    You can create a ScoreManager script to store scores of each level using PlayerPrefs and attach this script to a GameObject in the first scene.

    public class ScoreManager: MonoBehavior {
    
        public static ScoreManager Instance;
        const string LEVEL_KEY = "SCORE_";
        const string MAX_LEVEL_KEY = "MAX_LEVEL";
    
        public static int MAX_LEVEL {
            get { return PlayerPrefs.GetInt(MAX_LEVEL_KEY, 1); }
            set {
                if(value > MAX_LEVEL) {
                    PlayerPrefs.SetInt(MAX_LEVEL_KEY, value);
                }
            }
        }
    
        void Awake() {
            if(Instance != null) {
                Destroy(this.gameObject);
                return;
            }
            Instance = this;
            DontDestroyOnLoad(this);
        }
    
        public void SaveScore(int level, float score) {
            PlayerPrefs.SetFloat(LEVEL_KEY + level, score);
            MAX_LEVEL = level;
        }
    
        public float GetScore(int level) {
            return PlayerPrefs.GetFloat(LEVEL_KEY + level, 0);
        }
    
        public bool IsLevelUnlocked(int level) {
            // You can write your own level-unlock logic here.
            return level <= MAX_LEVEL;
        }
        ...
    }
    

    Then you can just call its functions and properties from other scripts.

        ...
        public void GameOver() {
            ScoreManager.Instance.SaveScore(level, score);
        }
        ...
    

    Having all LevelManger scripts with DontDestroyOnLoad will cause a memory leak and sometimes it will affect the game performance.

提交回复
热议问题