Datastore Not Working (Egg Hunt System)

Hey there. I am trying to make an egg hunt system, but the problem I am having is everytime the player rejoins they can get the eggs again. I want the EggStore to save the eggs that they have previously collected, but it doesn’t seem to work.

local badgeid = nil
local badgeservice = game:GetService("BadgeService")

local dss = game:GetService("DataStoreService")
local ds = dss:GetDataStore("EggStoreTest")

local eggs = game.Workspace.Eggs

local function CollectEgg(plr,v)
	local db = false
	
	local collected = false

	if db == false then
		db = true
		
		if data then
			for a,b in pairs(data) do
				if b == v.Name then
					collected = true
				end
			end
		end

		if collected == false then
			ds:UpdateAsync(plr.UserId, function(old)
				old = old or {}
				table.insert(old,v.Name)
				return old
			end)

			plr.Eggs.Value += 1

			if v.Golden then
				if v.Golden.Value == true then
					plr.leaderstats.Coins.Value += 10000
				else
					plr.leaderstats.Coins.Value += 1000
				end
			end
		end
		
		wait(0.5)
		db = false
	end
end

game.Players.PlayerAdded:Connect(function(plr)
	local stats = Instance.new("Folder",plr)
	stats.Name = "leaderstats"
	
	local Coins = Instance.new("IntValue",stats)
	Coins.Name = "Coins"
	Coins.Value = 0
	
	local EggsValue = Instance.new("IntValue",plr)
	EggsValue.Name = "Eggs"
	EggsValue.Value = 0
	
	local data = ds:GetAsync(plr.UserId)
	
	local CollectedEggs = nil
	
	if data then
		CollectedEggs = data
		
		for i,v in pairs(data) do
			EggsValue.Value += 1
		end
	end
	
	for i,v in pairs(eggs:GetChildren()) do
		v.Touched:Connect(function(hit)
			if hit.Parent then
				if hit.Parent:FindFirstChild("Humanoid") then
					CollectEgg(plr,v)
				end
			end
		end)
	end
end)

Any help would be appreciated! Thanks,

1 Like

On lines 17-18 data is not defined.

If you mean the data variable that was assigned on line 60, you should remove local to make it a variable that can be accessed from all the script

-- change line 60 to:
data = ds:GetAsync(plr.UserId)