I've been making a script where you can daily get a "Golden Ticket," and redeem it somewhere else, with also having some Chips. I can't, for the love of my life, figure out what's wrong with this. It's just having trouble saving, it gets the values if you don't have data, but you should have some when you rejoin. Any help?
local DataStoreService = game:GetService('DataStoreService')
local playerData = DataStoreService:GetDataStore('PlayerData')
local hourWait = 24
local function onPlayerJoin(player)
local leaderstats = Instance.new('Folder')
leaderstats.Name = 'leaderstats'
leaderstats.Parent = player
local chips = Instance.new("IntValue")
chips.Name = 'Chips'
chips.Parent = leaderstats
local ticket = Instance.new('IntValue')
ticket.Name = 'Tickets'
ticket.Parent = leaderstats
local timeNow = os.time()
local playerUserId = 'Player_'..player.UserId
local data = playerData:GetAsync(playerUserId)
if data then
ticket.Value = data['Tickets']
chips.Value = data['Chips']
local timeSinceLastClaim = timeNow - data
if (timeSinceLastClaim / 3600) >= hourWait then
--Eligible for reward :)
game.ReplicatedStorage.ShowDailyReward:FireClient(player, hourWait)
local connection
connection = game.ReplicatedStorage.ClaimDailyReward.OnServerEvent:Connect(function(triggeringplayer)
if triggeringplayer == player then
print("Reward Claimed")
player.leaderstats.GoldenChip.Value = player.leaderstats.GoldenChip.Value + 1
playerData:SetAsync(playerUserId,os.time())
connection:Disconnect()
end
end)
else
print("Player is uneligible currently.")
end
else
local playerUserId = 'Player_'..player.UserId
ticket.Value = 0
chips.Value = 1000
game.ReplicatedStorage.ShowDailyReward:FireClient(player, hourWait)
connection = game.ReplicatedStorage.ClaimDailyReward.OnServerEvent:Connect(function(triggeringplayer)
if triggeringplayer == player then
print("Reward Claimed")
player.leaderstats.GoldenChip.Value = player.leaderstats.GoldenChip.Value + 1
playerData:SetAsync(playerUserId,os.time())
connection:Disconnect()
end
end)
end
end
local function create_table(player)
local player_stats = {}
for _, stat in pairs(player.leaderstats:GetChildren()) do
player_stats[stat.Name] = stat.Value
end
return player_stats
end
local function onPlayerExit(player)
local player_stats = create_table(player)
local success, err = pcall(function()
local playerUserId = 'Player_'..player.UserId
playerData:SetAsync(playerUserId, player_stats)
end)
if not success then
local playerUserId = 'Player_'..player.UserId
pcall(function()
local timeVal = os.time()
playerData:SetAsync(playerUserId)
end)
print("Saved because you are a new player!")
end
end
game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)
