Hello! This guide will help you create your first data store on Roblox! In this guide, I will be using Datastore1. To use this guide efficiently, you need to understand basic syntax. Follow the steps below.
Step 1 - Create Leaderstats
In the image above, you should already know how to create leaderstats. Datastore works with any type of data but for this guide, leaderstats is the most convenient to follow through on. In leaderstats, create a value called "Cash". This is the value that you will store and retrieve from the servers.
Step 2 - Understanding Functions
Before you use Datastore for your leaderstats, you need to understand the functions for leaderstats. These are the main leaderstats that you will use most of the time.
local dataStoreService = game:GetService("DataStoreService") - Getting the DataStoreService from Roblox servers.
local CashDataStore = dataStoreService:GetDataStore("Currency") - Creating or getting a pre-existing Datastore file. You can name it anything inside of the quotation marks.
CashDataStore:GetAsync(plr.UserId) - By using this function, you are looking in the file and searching for a value with the title of the player's user ID. If you use the user ID, it is connected to the player when they change their name. This function returns the value put in with SetAsync.
CashDataStore:SetAsync(plr.UserId, 50) - By using this function, you are setting a value connected to another player in the file. you can set any value in the second parameter. Using "plr.UserId" in the first parameter is used in the same manner as in GetAsync's explanation.
Step 3 - Connecting the functions
Put the variable at the very top so it runs first. Then in the PlayerAdded function, get rid of the previous cash.Value line. As seen in lines 11-16, is sees if the player has played before by testing if the value is nil and then setting the value to 0 and setting the datastore value to 0. But if the value is not nil, is just sets the value to the current datastore value.
Step 4 - Adding the Player Leave Function
Underneath the PlayerAdded function, add a PlayerRemoving event to set the players datastore value to the leaderstat value to when the player leaves. pcall senses if the function fails. Using pcall is very necessary to use in any datastorage instances.
Step 5 - You're done!
Make sure that you publish your game to get the DataStorage services. Thank you for following along with this guide. Please message me if you find any errors with my code or problems with my guide. Thank you!