2016-07-27 89 views
1

我在Android上遇到PlayerPrefs問題。我希望我的教程只顯示一個時間,所以我寫了這個代碼:PlayerPrefs不適用於Android或編輯器

void Awake(){ 
     firstTime = false; 
     hasPlayed = PlayerPrefs.GetInt ("hasPlayed"); 
     if (hasPlayed == 0) { 
      firstTime = true; 
     } else { 
      PlayerPrefs.SetInt ("hasPlayed", 1); 
      firstTime = false; 
      PlayerPrefs.Save(); 
     } 
} 

一旦建成,並在手機測試中,APK不會創建任何文件夾/數據或什麼的,因此,將教程每次展示我運行遊戲。

+0

嘗試登錄hasPlayed'的'值。你也可以嘗試在'GetInt(「hasPlayed」,0)中添加第二個參數;'確保你得到0作爲默認值。 –

+0

你只是忘了GetInt上的「,0」 – Fattie

回答

1

PlayerPrefs.GetInt需要另一個參數,您可以使用該參數返回值,如果提供的密鑰確實存在不存在。檢查hasPlayed密鑰是否存在,默認值爲0。如果密鑰不存在,它將返回該默認值,即0

如果它返回0,請將hasPlayed設置爲1然後播放您的教程。如果它返回1,這意味着該教程已經播放過。類似this的問題,但需要一點修改。

這是它應該是什麼樣子:

void Start() 
{ 
    //Check if hasPlayed key exist. 
    if (PlayerPrefs.GetInt("hasPlayed", 0) == 1) 
    { 
     hasPlayed(); 
    } 
    else 
    { 
     //Set hasPlayed to true 
     PlayerPrefs.SetInt("hasPlayed", 1); 
     PlayerPrefs.Save(); 

     notPlayed(); 
    } 
} 


void hasPlayed() 
{ 
    Debug.Log("Has Played"); 
    //Don't do anything 
} 

void notPlayed() 
{ 
    Debug.Log("Not Played"); 
    //Play your tutorial 
} 

//Call to reset has played 
void resetHasPlayed() 
{ 
    PlayerPrefs.DeleteKey("hasPlayed"); 
} 
+0

@Cabrra是的,可以使用'PlayerPrefs.HasKey'。我實際上使用了'PlayerPrefs.GetInt',這樣可以擴展更多。例如,大多數遊戲在每個級別都有不同的教程。上面的代碼可以很容易地擴展到通過添加'else if(PlayerPrefs.GetInt(「hasPlayed」,0)== 2)'來檢查玩家最後播放哪個教程以及下一個播放哪個教程。您可以添加儘可能多的教程。 'PlayerPrefs.HasKey'不能單獨做這件事,並且仍然需要'PlayerPrefs.GetInt'結合它,這會使代碼變得更長。 – Programmer

+0

另外'GetInt(string key,int defaultValue);'在引擎蓋中執行'PlayerPrefs.HasKey'。它縮短了代碼。只有當你想知道密鑰是否存在時才需要'PlayerPrefs.HasKey'。在我的情況下,我想知道它是否存在,並且也可以在不使用兩個函數的情況下獲取值。 – Programmer

+1

完美,這句話:PlayerPrefs.GetInt(「hasPlayed」,0)== 1做了這個把戲。非常感謝! – user1423168

相關問題