DataStore not working

I want it so that it saves the players level when they leave and gives it to them when they join back. It saves the level to the table but when I join back the table is empty. I’m new to data store can someone explain why this is happening?

can we have the script to the DataStore?

Module Script

datastoreservice = game:GetService("DataStoreService")
mydatastore = datastoreservice:GetDataStore("MyDataStore")

levels = {}

SaveController = {}

function SaveController.SaveData(player, level)
	mydatastore:SetAsync(player.UserId, level)
	table.insert(levels, player.UserId, level)
	print("Data Saved")
end

function SaveController.CheckData(player)
	print(player.UserId)
	mydatastore:GetAsync(player.UserId)
	return levels
end
	
return SaveController

Join Script

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

	local level = nil
	local success, errormessage = pcall(function()
		levels = data.CheckData(plr)
	end)
	if success then
		print("tabel found")
	end
	for i, v in pairs(levels) do
		print(i, v)
		if i == plr.UserId then
			level = v
		end
	end
	if level == nil then
		level = 1
		print("Not Found")
	end
end)

Why put it in a table when you can just return the player’s level?

https://developer.roblox.com/en-us/api-reference/function/GlobalDataStore/GetAsync


image

also, you are inserting elements to the table after you have saved, so it’s wasted. You would simply return the level.

in the module script, in this:

function SaveController.CheckData(player)
	print(player.UserId)
	mydatastore:GetAsync(player.UserId)
	return levels
end

i think you meant to return the DataStore data, so you should do this instead:

function SaveController.CheckData(player)
	print(player.UserId)
	return mydatastore:GetAsync(player.UserId) -- or defaultStats -- in case they dont have any data if its the first time they have played, for example
end
1 Like