MZ [Help] How to save and load game via script call?

Hello everyone,
So, basically I want to make custom save and load scene via event.
I get some trouble to save and load data via script call. here's That I use via script call.
Let say I want to save in the slot number 1.

JavaScript:
$gameSystem.onBeforeSave();
DataManager.saveGame(1);

Here's when I load data via script call.
JavaScript:
DataManager.loadGame(1);
        const mapId = $gameMap.mapId();
        const x = $gamePlayer.x;
        const y = $gamePlayer.y;
        const d = $gamePlayer.direction();
        $gamePlayer.reserveTransfer(mapId, x, y, d, 0);
        $gamePlayer.requestMapReload();
SceneManager.goto(Scene_Map);

The think, the script was success when I save and load in the same map.
But, If I load in different map I got an error.

JavaScript:
TypeError
Cannot read property 'pages' of undefined

So, did you guys have any idea to solve this?
Thank you!
It could be because the loading did not complete before you try and move your player SceneManager.goto(Scene_Map); to the new map area.

Try and add a condition to the script, maybe something like :


JavaScript:
DataManager.loadGame(1).then(function(success) {
    if (success) {
        const mapId = $gameMap.mapId();
        const x = $gamePlayer.x;
        const y = $gamePlayer.y;
        const d = $gamePlayer.direction();
       
        $gamePlayer.reserveTransfer(mapId, x, y, d, 0);
        SceneManager.goto(Scene_Map);

        $gamePlayer.requestMapReload();
    } else {
        console.error("Failed to load game.");
    }
});

Notice I switched $gamePlayer.requestMapReload(); after the SceneManager.goto(Scene_Map); part.
This should ensure the map data isn't being accessed before it's available.
Hello Artille, thank you for giving the idea!
I'll try it, but the game have same issue like i mention before.

So, I try to save via open save via event and load the game with the script can be load perfectly.
I think, the issue maybe in the saving the game via script call. Maybe something missing when I call the save file(?)
After the error happens, press F8 or F12 to open the dev tools window and select the Console tab in that window. Detailed error information will appear here, usually in red text. Can you attach a screenshot of that information? 👋

Note that MZ's "save game" script call usually has an extra line like this at the start:
JavaScript:
$gameSystem.setSavefileId(1);
If you're only using 1 save slot, though, then you might not need that.

Like @Artille says, load/save is asynchronous in MZ, so stuff can still keep updating while the load/save is happening. That's not usually a problem, because the load/save screens don't do anything except wait for the operation to complete.

When trying to save/load from the map, though, things get complicated. Artille addressed part of the problem, but the current event will also continue processing commands, without waiting for the save/load to complete first. That can be solved with a loop, e.g.
Spoiler: event suggestion
Script:
JavaScript:
$gameTemp.loading = true;
DataManager.loadGame(1).then(() => {  // on success
  SoundManager.playLoad();
  // Transfer also handles fade in/out.
  $gamePlayer.reserveTransfer(
    $gameMap.mapId(),
    $gamePlayer.x,
    $gamePlayer.y,
    $gamePlayer.direction(),
    0  // 0 = black, 1 = white, 2 = none
  );
  // Only reset if game version has changed.
  if ($gameSystem.versionId() !== $dataSystem.versionId)
    $gamePlayer.requestMapReload();
  // Renew map scene.
  SceneManager.goto(Scene_Map);
  // Restore BGM/BGS/playtime from save.
  $gameSystem.onAfterLoad();
}).catch(() => {  // on error (e.g. save doesn't exist)
  SoundManager.playBuzzer();
}).finally(() => {  // always
  delete $gameTemp.loading;
});
Followed by:

◆Loop ◆If:Script:$gameTemp.loading ◆Comment:Check again next frame. ◆Wait:1 frame ◆ :Else ◆Break Loop ◆ :End ◆ :Repeat Above ◆Text:None, None, Window, Bottom : :Load game failed, oh no!

Other map stuff, e.g. Parallel events and plugins, will also continue processing during save/load. That's why it is important to know more details about the error.
Hello Artille, thank you for giving the idea!
I'll try it, but the game have same issue like i mention before.

So, I try to save via open save via event and load the game with the script can be load perfectly.
I think, the issue maybe in the saving the game via script call. Maybe something missing when I call the save file(?)
The issue with save is likely the same as with load.
It could be that the save state isn't fully prepared before you invoke the save function.

I see your save script is rather simplistic
JavaScript:
$gameSystem.onBeforeSave();
DataManager.saveGame(1);

This might work if there is not alot of data to save, however as the file becomes bigger, it might become troublesome if you ask the save function to save data it hasn't been able to process entirely.

Try the same approach as I mentionned with loading
Something like :
JavaScript:
    try {
        $gameSystem.onBeforeSave();

        // Introduce a short delay to ensure all processes are stable
        setTimeout(() => {
            DataManager.saveGame(1).then(function(success) {
                if (success) {
                    console.log("Game saved successfully in slot 1.");
                } else {
                    console.error("Failed to save game.");
                }
            }).catch(function(error) {
                console.error("Error during save operation:", error);
            });
        }, 100); // 100ms delay
    } catch (error) {
        console.error("Unexpected error during save preparation:", error);
    }

This includes logs to see what is going wrong should it not work.
At least you can debug it more efficiently.

You can also folow @caethyril's advise and use a loading/saving flag
JavaScript:
try {
        // Set saving flag
        $gameTemp.saving = true;
        
        // Ensure game state is prepared
        $gameSystem.onBeforeSave();

        // Introduce a short delay to ensure all processes are stable
        setTimeout(() => {
            // Perform the save operation
            DataManager.saveGame(1).then(function (success) {
                if (success) {
                    console.log("Game saved successfully in slot 1.");
                } else {
                    console.error("Failed to save game.");
                }
            }).catch(function (error) {
                console.error("Error during save operation:", error);
            }).finally(function () {
                // Clear saving flag
                delete $gameTemp.saving;
            });
        }, 100); // 100ms delay
    } catch (error) {
        console.error("Unexpected error during save preparation:", error);
    }
Just to mention it: I did test my suggestion before posting. It worked for me, so I suspect OP's problem is with a plugin. Guessing from the error, maybe an event spawner.

DataManager.saveGame builds the save data object synchronously (makeSaveContents), then begins its async processing. So I believe the data-to-save is guaranteed to be coherent. However, I can see that it might include references that a plugin (for whatever reason) would not expect to be present in save data.

Personally I got tired of trying to do this with script calls and did wrote a plugin for it: feature D21 of Cae_Tweaks ("synchronous save/load plugin commands"). Note that it uses essentially the same approach as the script call & event that I suggested here, so any problems with one will probably be present in both.

JavaScript:
// Introduce a short delay to ensure all processes are stable
setTimeout(() => {
I guess you're thinking it's best to save between mechanical frame updates. Isn't using setTimeout to do so a gamble, though? Especially with a wait time of 100 ms = 6 frames at 60 fps. If you're aiming for something like "save at the end of Game_Map#update" then I'd recommend a plugin for reliable timing. Maybe I'm missing something. 😅

Some other notes on your code:
  1. The setTimeout function gets invoked in another context, unaffected by the try-catch block.
  2. DataManager.saveGame fulfills with 0, so I don't think "saved successfully" will ever show.
  3. Your second example is missing a }) for the finally clause.
I guess you're thinking it's best to save between mechanical frame updates. Isn't using setTimeout to do so a gamble, though? Especially with a wait time of 100 ms = 6 frames at 60 fps. If you're aiming for something like "save at the end of Game_Map#update" then I'd recommend a plugin for reliable timing. Maybe I'm missing something. 😅

Some other notes on your code:
  1. The setTimeout function gets invoked in another context, unaffected by the try-catch block.
  2. DataManager.saveGame fulfills with 0, so I don't think "saved successfully" will ever show.
  3. Your second example is missing a }) for the finally clause.
I see, my logic wasn't all that complex.
I just thought of giving it a little bit more time before actually invoking the saveGame.

1. You are right about the setTimeout, I didn't think that through.
I could wrap it in its own try-catch block though ^^

2. My knowledge off the core mechanics isn't that complete ^^, my bad.
I guess one could hook into the game loop and make a function that overrides the update method, but that would be farfetched for a script.

3. Copy-paste didn't work as planned 👋


Maybe I'll try and write a plugin about this 😀
But for now, just stick to @caethyril's method
Hello there!
Thank you for the replies!

Somehow, When I try to save and load in the same map, the load game can be run perfectly.
But when I load the game in different map, I got some error like I mention before.

Here's the error
Untitled.png


Here's the error from @caethyril script when I load in different map.
Untitled.png


Since I can save or load in the same map.
for now, I decide to make the save/load scene in a one map to avoid these error.
As mentionned before, a plugin might interfere with the desired behavior.

What plugins are you using and did you try to disable them (try all of them at first) to see if it works as intended?

If plugins are the cause, knowing which one might help solve this.
Looking at that console screenshot, it seems to be all core stuff. Plugins might still be involved, but I'd guess this is an issue with the script call.

I now remember seeing a similar problem in another thread (link):
I increased the number of events on the map that manage the title by the number of events on the map to load, and it was loaded without errors.
I wonder if it's related to the scene update cycle: if the load can complete part-way through a scene update, that could cause a temporary mismatch between $dataMap and $gameMap, giving this kind of error.

I think it should be possible to work around that with a plugin that implements a "request" system, e.g.
  • Request "load game" in the event;
  • At the end of the update cycle, if load was requested, start loading;
  • Skip main updates while a load operation is in progress.
Rough idea (untested):
Spoiler: plugin code
JavaScript:
/*:
 * @target MZ
 * @plugindesc Adds a script call to load a game.
 * @author Caethyril
 * @url https://forums.rpgmakerweb.com/threads/170077/
 * @help In a Script command, you can use this:
 *          loadGame(slotId)
 *     e.g. loadGame(0)   - loads autosave
 *     e.g. loadGame(1)   - loads save ID 1
 * It should load synchronously, blocking updates until complete.
 *
 * Free to use and/or modify for any project, no credit required.
 */
;void (() => {
'use strict';
  let loadId = -1;
  let busy = false;
  globalThis.loadGame = function(slotId) { if (slotId >= 0) loadId = slotId; };
  const load = function() {
    if (loadId >= 0) {
      busy = true;
      DataManager.loadGame(loadId).then(() => {
        SoundManager.playLoad();
        $gamePlayer.reserveTransfer(
          $gameMap.mapId(),
          $gamePlayer.x,
          $gamePlayer.y,
          $gamePlayer.direction(),
          0  // fade black
        );
        if ($gameSystem.versionId() !== $dataSystem.versionId)
          $gamePlayer.requestMapReload();
        SceneManager.goto(Scene_Map);
        $gameSystem.onAfterLoad();
      }).catch(() => {
        SoundManager.playBuzzer();
      }).finally(() => {
        busy = false;
      });
      loadId = -1;
      return true;
    }
    return false;
  };

  // Patch - block scene updates while busy loading.
  void (alias => {
    SceneManager.updateMain = function() {
      if (!busy)
        alias.apply(this, arguments);
      load();
    };
  })(SceneManager.updateMain);

})();
That might have side-effects, I'll investigate more later~
Artille :
I already off all my plugin, still same. Somehow MZ has different architecture than MV. cuz I can do this easily on MV.

​

caethyril:​

I'll try it after come back to my PC. xD

Anyway, thank you guys.
Somehow this discussion make me want to complete my game as soon as possible. haha
😅 Oops, I nearly forgot about this. I couldn't manage to reproduce either error, but did the small plugin I suggested help fix the problem? Or have you just given up on loading from a different map?

Original thread: https://forums.rpgmakerweb.com/threads/help-how-to-save-and-load-game-via-script-call.170077/