Reputation: 9065
I am using PlayerPerfabs to store player data like which level the player has unlocked and the point has got during the game, and I want the PlayerPerfabs data updated regularly(like per 5 seconds) during playing, so I made a class called ApplicationModel to hold the global data like points player get the level info etc..
public ApplicationModel: MonoBehaviour{
public static int point {get;set;}
//try to load the PlayerPerfabs when start game.
static ApplicationModel(){
if(PlayerPerfabs.HasKey("point")){
point = PlayerPerfabs.GetInt("point");
}else{
point = 0;
}
}
//coroutine to set the data to PlayerPerfabs
IEnumerator Save()
{
while (true)
{
Debug.Log("setting playerperfab ....");
yield return new WaitForSeconds(5f);
ApplicationModel.RestorePerfab();
}
}
public static void RestorePerfab(){
PlayerPerfabs.SetInt("point", point);
}
private void Start(){
StartCoroutine(Save());
}
}
But the coroutine was never executed according to the console log (cause the log was never printed).
Maybe because I didn't attach this script to a gameobject but once I attach this to a game object, then when the scene changed or that gameobject is destroyed, the regularly saving will ended, right? So how to do this?
Upvotes: 2
Views: 53
Reputation: 2923
You need to create a GameObject
and then attach this script to it if you want it to work. If you're changing scenes and want it to continue working you could call DontDestroyOnLoad
on that GameObject
and it won't get destroyed when you switch scenes.
Upvotes: 2