Saving Player Data

Saving Player Data

15 min

Roblox allows data to be saved on its servers. The primary purpose of this feature is to store player data between sessions, keeping their stats, inventory, and other data intact. In this tutorial, we’ll create a system that automatically stores a player’s money and experience so that it can be retrieved when they play the game again.

Creating a Data Module

Before we dive into data storage, let’s set up the system which keeps track of a player’s money and experience during a game session. We’ll start by creating a ModuleScript, a special type of script that can be referenced from other scripts. An ideal place for this ModuleScript is within ServerStorage.

Saving Player Data

Now let’s start storing actual information using data stores.

Initialize the Data Store

First we’ll add a new variable for the data store in the same ModuleScript and call DataStoreService/GetDataStore|GetDataStore() to open a new PlayerData data store.

Read/Write Initial Data

Next, let’s change how the setupPlayerData() function works. Currently, it just creates new data for a player when they join the game, but that data isn’t saved anywhere! Now, with access to the playerData data store, we can call GlobalDataStore/GetAsync|GetAsync() to check if it’s holding any information for the player. If that call returns valid data, we save it to the sessionData table; otherwise we save new player data to the sessionData table.

Save Data on Exit

It’s good practice to save a player’s data when they exit the game. This can be done with a new savePlayerData() function bound to the Players/PlayerRemoving|PlayerRemoving event.


Lastly, it’s useful to make the system handle unexpected events like game crashes. We can do this with a function that waits for AUTOSAVE_INTERVAL seconds (60), loops through all of the players in the sessionData table, and uses the savePlayerData() function to save the current information. Note that this function is initially run in a coroutine using the spawn() function.

With all of the above implemented, we now have a simple stat saving system that automatically saves the players’ data.

Handling Data Store Failures

Requests to data stores, like all network calls, may occasionally fail due to poor connectivity or other issues. As you learned in the Articles/Data store|Data Stores article, these calls should be wrapped in pcall() to catch and handle errors. Let’s apply this practice to the current script:

Data Store Retries

As a final measure of reliability, it can be useful to retry data saves if the first attempt fails. This functionality can be added to the existing script with a simple repeat loop in the savePlayerData() function:

  • data
  • stats