Awarding a player every 24 hours

Hey! So I am trying to award a player 5 gems every 24 hours, though I am not to sure how, as I want it to add 5 gems to the data store. This is what I have

--variables
local secondsinday = 86400
local Datastore = game:GetService("DataStoreService")
local DailyRewards = Datastore:GetDataStore("DailyRewards")
local gemdaatastore = Datastore:GetDataStore("Gems")
--functions
function reward(player)
	player.leaderstats.gems.Value += 5
	
	DailyRewards:SetAsync(player.UserId, os.time())
	gemdaatastore:IncrementAsync(player.UserId, 5)
end

function loadLeaderstats(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	local gems = Instance.new("IntValue")
	gems.Name = "gems"
	gems.Value = gemdaatastore:GetAsync(player.UserId) or 0
	gems.Parent = leaderstats
end


game.Players.PlayerAdded:Connect(function(player)
	loadLeaderstats(player)
	
	local lasttimejoined = DailyRewards:GetAsync(player.UserId)
	
	if not lasttimejoined then
		reward(player)
	else
		local diffTime = math.abs(os.difftime(os.time(),lasttimejoined))
			
		if diffTime >- secondsinday then
			reward(player)
		end
	end
end)
1 Like

I believe you accidently did >- instead of >=. Also, the math.abs is unnecessary.

Code:

--//Services
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")

--//Variables
local DailyRewards = DataStoreService:GetDataStore("DailyRewards")
local GemDataStore = DataStoreService:GetDataStore("GemDataStore")

--//Controls
local secondsInADay = 86400

--//Functions
local function reward(player)
	player.leaderstats.gems.Value += 5

	DailyRewards:SetAsync(player.UserId, os.time())
end

local function loadLeaderstats(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local gems = Instance.new("IntValue")
	gems.Name = "gems"
	gems.Value = GemDataStore:GetAsync(player.UserId) or 0
	gems.Parent = leaderstats
end

Players.PlayerAdded:Connect(function(player)
	loadLeaderstats(player)

	local lasttimejoined = DailyRewards:GetAsync(player.UserId)

	if not lasttimejoined then
		reward(player)
	else
		local diffTime = os.difftime(os.time(), lasttimejoined)

		if diffTime >= secondsInADay then
			reward(player)
		else
			task.wait(secondsInADay - diffTime)
			
			if player:IsDescendantOf(Players) then
				reward(player)
			end
		end
	end
end)

Players.PlayerRemoving:Connect(function(player)
	local success, errorMessage = pcall(function()
		GemDataStore:SetAsync(player.UserId, player.gems.Value)
	end)
	
	if not success then
		warn(errorMessage)
	end
end)

I also made it so that if they reach the 24 hour mark while still in the game, it gives them the reward. You also should only be saving when the player leaves, and using multiple data stores is not good for performance.

1 Like