PcoWSkbVqDnWTu_dm2ix

Saving Data – Introduction

Saving Data – Introduction

5 min

DataStoreService saves data that persists between game sessions, for example a player’s gold/cash, experience points, or items in their inventory. Saved data is accessible from any place in a game and also between servers.

Enabling Studio Access

By default, games tested in Studio cannot access data stores, so you must enable them.

  1. From the Home tab, open the Game Settings window. If your game is not published, you’ll be prompted to do so.
  1. In the Security section, turn on Enable Studio Access to API Services.
  2. Click Save to register your changes.

Accessing Data Stores

Data stores are initially created and accessed by a unique name. For example, a data store named PlayerGold can store each player’s gold during and between game sessions.

  1. Create a new Script within ServerScriptService called DataStoreTest.
  1. Data stores are managed by DataStoreService, so get the service on the first line.
  1. Call DataStoreService/GetDataStore|DataStoreService:GetDataStore() with the string "PlayerGold". This will access the PlayerGold data store if it already exists, or create it otherwise.

Data returned by DataStoreService/GetDataStore|GetDataStore() is not sorted. This isn’t a concern when reading specific individual keys, but sorted data fetched via DataStoreService/GetOrderedDataStore|GetOrderedDataStore() is essential for user interfaces like persistent leaderboards.


Saving Data

A data store is essentially a dictionary, like a Lua table. Each value in the data store is indexed by a unique key, for instance the player’s unique Player/UserId|UserId or simply a named string.

Player Data Game Data
Key Value
31250608 50
351675979 20
505306092 78000
Key Value
ActiveSpecialEvent SummerParty2
ActivePromoCode BONUS123
CanAccessPartyPlace true

To save data into the PlayerGold data store, call GlobalDataStore/SetAsync|SetAsync() with the key and a value:

Reading Data

To read data from a data store, call GlobalDataStore/GetAsync|GetAsync() with the desired key name:

Testing

Once you’ve finished the script, the PlayerGold data store can be tested.

  1. Click the Run button.
  1. If everything is correct, the playerGold value should be printed to the Output window. Note that it may take a few seconds, as the functions must connect to data store servers.

Sample Place

Now that you understand basic data store usage, test it out in a sample place.

Gold Rush

Gather as many gold chunks as you can to set a personal record that will persist between game sessions.
Tags:
  • data
  • data store
  • player data
  • game data