Data store isnt saving and/or loading to storage

Im trying to make a datastore for levels so it saves whenever u leave and loads whenever you join. But it just doesnt want to do it. Any fix?

Heres my code so far

local dataStoreService = game:GetService("DataStoreService")

local dataStore = dataStoreService:GetDataStore("LevelStorage")

local function saveData(player) -- The functions that saves data

local tableToSave = {

player.leaderstats.Level.Value

}

local success, err = pcall(function()

dataStore:SetAsync(player.UserId, tableToSave) -- Save the data with the player UserId, and the table we wanna save

end)

if success then

print("Data has been saved!")

else

print("Data hasn't been saved!")

warn(err)

end

end

game.Players.PlayerAdded:Connect(function(plr)

local leaderstats = Instance.new("Folder", plr)

leaderstats.Name = "leaderstats"

local cash = Instance.new("NumberValue", leaderstats)

cash.Name = "Cash"

cash.Value = 0

local OwnsTycoon = Instance.new("BoolValue", plr)

OwnsTycoon.Name = "OwnsTycoon"

OwnsTycoon.Value = false

local level = Instance.new("IntValue",leaderstats)

level.Name = "Level"

local data

local success, err = pcall(function()

data = dataStore:GetAsync(plr.UserId)

end)

if success and data then

level.Value = data[1]

else

print("The player has no data!")

end

end)

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

local success, err = pcall(function()

saveData(player)

end)

if success then

print("Data has been saved")

else

print("Data has not been saved!")

end

end)

game:BindToClose(function()

for _, player in pairs(game.Players:GetPlayers()) do

local success, err = pcall(function()

saveData(player)

end)

if success then

print("Data has been saved")

else

print("Data has not been saved!")

end

end

end)
2 Likes

Check the line that you save on, you use level key to load the data but save with key Level so make them both the same aka all lower letters.

Here is a great beginner tutorial for implementing data stores, and explains every step of the process very easily:

Edit: Also, it helps to have the code formatted to make it easier for people to read and follow along. And also let us know what the output is printing.

I did that but still same problem occures

Ok i did this but it says in the output “data has been saved” but when i join back it doesnt load. Ive edited the message to the new code. Sometimes also i get an error “Datastore request was added to queue”

Add in a print statement here to see if it loads in the the new data

Have you enabled API services?

I joined set my level to 10 left it said “data has been saved” i join back and i am still level 1 with the print “Value has loaded in”

Yes and i have tested it in studio and in the game

I fixed it by having a seperate script that autosaves every 30 seconds