- Home /
How to wait to set PlayerPrefs?
Hello!
I am using an asset that sends all PlayerPrefs data to iCloud once they are updated. The problem is, that when the user for example collects a coin, the game instantly sends the data to iCloud and it creates a 0.5s delay each time it happens, but only once per level (first time).
Is it possible to "store" the playerprefs and then set them when a bool turns true?
Or do you have another solution for me? Thanks a lot in advance.
Answer by Cherno · Jul 03, 2015 at 10:14 PM
You can use a Coroutine. Pseudocode:
if(CoinIsPickedUp) {
StartCoRoutine(MyCoroutine(PlayerPref values you want to save));
}
IEnumerator MyCoroutine(PlayerPref values you want to save) {
while(myBool == false) {
yield return null;
}
//Save PlayerPref values you want to save
yield return null;
}
Will this work if the user resets the level?
In other words, will it carry over if the following is called:
int currentLevel = Application.loadedLevel;
Application.LoadLevel (currentLevel);
And is it
if(CoinIsPickedUp) {
StartCoroutine($$anonymous$$yCoroutine());
}
void OnTriggerEnter ()
{
if (Coin.gameObject.tag == "Coin") {
if (!collected) {
collected = true;
CoinController.coins++;
Statistics.totalCoinsCollected++;
CoinController.coinsCollectedThisLevel++;
StartCoroutine(SaveCoinPrefs());
}
Destroy (Coin.gameObject);
}
}
IEnumerator SaveCoinPrefs() {
while(CarTouchControls.sendToCloud == false) {
yield return null;
}
PlayerPrefs.SetInt ("Coins", CoinController.coins);
PlayerPrefs.SetInt ("TotalCoinsEver", Statistics.totalCoinsCollected);
yield return null;
}
Does this work? I get build errors for unrelated reasons at the moment so I can' test this.
I passed a parameter to the Coroutine because you wrote about "storing" the prefs before setting them. I see you use the CoinController to store it ins$$anonymous$$d.
The syntax look fine after cursory reading, if the logic is correct I can't say, it depends on how your scripts interact with each other.
IEnumerator SaveCoinPrefs() {
while(CarTouchControls.sendToCloud == false) {
yield return null;
}
PlayerPrefs.SetInt ("Coins", CoinController.coins);
PlayerPrefs.SetInt ("TotalCoinsEver", Statistics.totalCoinsCollected);
yield return null;
}
Is it right that both are yield return null;?
Yes, although I am not 100% sure if the second one is necessary. Coroutines have to have a return type, and I think it's the same as with other methods which have a return type: Every code path needs to end wit ha return. You can try commenting-out the second yield return null and see if it throws an error.
Your answer
Follow this Question
Related Questions
Google Cloud PlayerPrefs Plugin 0 Answers
Cloud recognition in Vuforia 0 Answers
Game/editor stops responding when going to Highscores 0 Answers
PlayerPrefs Player And Enemy Spawn 1 Answer
Save and Retrieve Score not working! 1 Answer