2014-07-02 21 views
1

問題:我需要用戶進入下一個場景的分數,沒有什麼複雜的,所以它可以說'做得好'得分'+分數。遊戲結構由三個場景組成,開始,結束,結束。我需要將比分從比賽場景中提供給最終場景。如何保持用戶分數並將其加載到下一個場景中?

問題:我該怎麼做?我已經看過單身人士& DontDestroyOnLoad函數,但我不知道如何使用它們或者什麼附加它們以及要保存什麼遊戲對象。

public class Score : MonoBehaviour 
{ 
    public int score = 0;     

    void Awake() 
    { 
     InvokeRepeating("increaseScore", 1, 1); 
    } 

    void Update() 
    { 
     score++; 
     // Set the score text. 
     guiText.text = "Score: " + score; 
    } 
} 

這是我的得分的代碼,如果它有幫助。

+0

使用xml文件也是一個選項。 – David

回答

1

你可以使用PlayerPrefs.SetIntPlayerPrefs.GetInt

// Save score to prefs before scene is destroyed 
PlayerPrefs.SetInt("score", score); 

然後:

// Load score when new scene is loaded 
score = PlayerPrefs.GetInt("score"); 

或者,你的分數類的清醒函數中,使用DontDestroyOnLoad使其遊戲物體不會被銷燬:

DontDestroyOnLoad(gameObject); 
1

用分數的靜態變量創建一個靜態類。這是最簡單的解決方案,您不需要使用playerPrefs。

public static ScoreManager 
{ 
    private static int score = 0; 

    public static void setScore(int s) 
    { 
     score = s; 
    } 

    public static int getScore() 
    { 
     return score; 
    } 
} 

靜態類在整個程序的執行過程中保持活躍狀態​​,不管你去哪個場景。

相關問題