DataStore

Learn how to make an auto-save for your game.

by SamirDevs

Author Avatar

We are gonna make the save section for the datastore now so the datastore saves your stats.

game.Players.PlayerRemoving:connect(function(player)

Find datastoreservice and leaderstats.

local datastore = game:GetService("DataStoreService"):GetDataStore(player.Name.."Stats"

Now you gotta find the players stats to save.

local statstorage = player:FindFirstChild("Stats"):GetChildren()

We gotta save every single stat of the players stats, and how we gonna save every single one of them?? yes, u gonna use GetChildren() which finds all the stats of the player We are gonna use "i,v for" to get the stat and save them.

for i =  1, #statstorage do
    datastore:SetAsync(statstorage[i].Name, statstorage[i].Value)
    print("saved data number "..i)

Then print and end.

end
print("Stats successfully saved")
end)

Load Stats Part:

Now we are gonna make the load part, which loads ur stats when the player joins!

Add player function like before and find Datastoreservice.

game.Players.PlayerAdded:connect(function(player)
        local datastore = game:GetService("DataStoreService"):GetDataStore(player.Name.."Stats")

add waitforchild so the datastore doesnt directly try to find the stats and do errors

    player:WaitForChild("Stats")
    wait(1)
    local stats = player:FindFirstChild("Stats"):GetChildren()

Find stats like before

    for i = 1, #stats do
    stats[i].Value = datastore:GetAsync(stats[i].Name)
    print("stat number "..i.." has been found")

aaaand END

        end
end)

The Results:

if u dont wanna spend soo much time at this bad tutorial then just copy this. the results would be

game.Players.PlayerRemoving:connect(function(player)
    local datastore = game:GetService("DataStoreService"):GetDataStore(player.Name.."Stats")

local statstorage = player:FindFirstChild("Stats"):GetChildren()
for i =  1, #statstorage do
    datastore:SetAsync(statstorage[i].Name, statstorage[i].Value)
    print("saved data number "..i)

end
print("Stats successfully saved")
end)


game.Players.PlayerAdded:connect(function(player)
        local datastore = game:GetService("DataStoreService"):GetDataStore(player.Name.."Stats")

    player:WaitForChild("Stats")
    wait(1)
    local stats = player:FindFirstChild("Stats"):GetChildren()
    for i = 1, #stats do
    stats[i].Value = datastore:GetAsync(stats[i].Name)
    print("stat number "..i.." has been found")
        end
end)

Happy coding!

Edit: fixed spelling errors.

View in-game to comment, award, and more!