Creating the SaveHandler script

Now, we create a script that allows us to call the functions that we just created from the preceding two scripts. First, we create a checkpoint system that saves game data at specific points within the game. Then, we create a way to allow the player to save their data whenever they want to. To get started, create a new script, and name it SaveHandler.

The checkpoint system

The first way in which we create to save and load data is a checkpoint system. Checkpoints are typically areas in the game world on reaching which the game will save the player's data. Add this function to allow the checkpoint to save:

void OnTriggerEnter(Collider other)
{
  if(other.tag == "SavePoint")
  {
    Camera.main.SendMessage("WriteToFile");
    Destroy(other.gameObject);
  }
}

This is a trigger-based method to save. When the player enters the triggered area, the game will save the player's data. Within the if statement, you can call any of the save functions we created. You should take note that this function also destroys the trigger object so that the player can't reactivate the checkpoint.

The save anywhere-anytime system

To allow the player to save their data anywhere they want and anytime they want, we add some kind of option for them to call it freely. This can be done by adding to the menu a key or a button, or both, that the player presses. For this example, we will let the player press keys on the keyboard to save and load. Add the following function to create this functionality;

void Update()
{
  if(Input.GetKeyUp(KeyCode.F1))
  {
    Camera.main.SendMessage("SaveEnemies");
  }
  if(Input.GetKeyUp(KeyCode.F2))
  {
    Camera.main.SendMessage("LoadEnemies");
  }
}

When the player presses the F1 key, we call the SaveEnemies function from the XML save system. If the player presses the F2 key, we call the LoadEnemies function from the XML save system. With this functionality, the players can save their progress at any time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.59