Page 1 of 1

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

Posted: Fri Jan 01, 2021 7:11 pm
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.)
}

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

Posted: Fri Jun 03, 2022 7:42 pm
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.

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

Posted: Fri Jun 03, 2022 8:22 pm
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.