[HOWTO] How To: Run Things On Start But After Save Data Is Applied

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
User avatar
Tony Li
Posts: 21977
Joined: Thu Jul 18, 2013 1:27 pm

[HOWTO] How To: Run Things On Start But After Save Data Is Applied

Post by Tony Li »

If you run something on start that depends on saved data that the save system has carried over from another scene or a loaded game, you may find that the saved data is not ready yet. This is due to the way the save system works.

Many scripts initialize themselves in Start() methods, and sometimes they take more than one frame to finish initialization. You don't want to apply the saved game data's state until the script has finished initializing; otherwise the initialization process may overwrite the state that you just applied.

You can configure the Save System component to wait any number of frames before applying the saved game data. By default, it waits one frame. If you need to access saved state at start, try setting Frames To Wait Before Apply Data to zero, or tick the saver's Restore On Start checkbox. If that doesn't resolve the issue, you can wait until the save system has applied the save data. To do this, hook into the SaveSystem.saveDataApplied C# event:

Code: Select all

void OnEnable() { PixelCrushers.SaveSystem.saveDataApplied += OnSaveDataApplied; }
void OnDisable() { PixelCrushers.SaveSystem.saveDataApplied -= OnSaveDataApplied; }  
void OnSaveDataApplied()
{
    // (We know the saved state has been applied, so we can trigger quests, etc., now.)
}
NotVeryProfessional
Posts: 145
Joined: Mon Nov 23, 2020 6:35 am

Re: [HOWTO] How To: Run Things On Start But After Save Data Is Appled

Post by NotVeryProfessional »

shouldn't this be

Code: Select all

public override void OnEnable() { base.OnEnable(); (then your code) }
?

At least for me, without this, the custom saver doesn't register itself anymore.
User avatar
Tony Li
Posts: 21977
Joined: Thu Jul 18, 2013 1:27 pm

Re: [HOWTO] How To: Run Things On Start But After Save Data Is Applied

Post by Tony Li »

The code in the original post is for non-Saver scripts. If your non-Saver script has a virtual base OnEnable() method, then yes you'll want to override it and also call the base method.

For Saver scripts, you don't need to worry about all this. The save system will automatically call ApplyData() at the right time.
Post Reply