How do I fix this currency give script

So I am making A script where the player can get coins by clicking a button that also gives a tool to the player.

The script keeps giving giving me this error:

15:29:14.642 - Tokens is not a valid member of Folder “Players.NotAid_n.leaderstats”

15:29:14.644 - Stack Begin

15:29:14.644 - Script ‘ServerScriptService.GivePlayerItem’, Line 4

15:29:14.645 - Stack End

I don’t really no where to start on this as this is my first time using currency that isn’t already made.

The Currency script I made:

local DataStoreService = game:GetService("DataStoreService")
local CurrencyStore = DataStoreService:GetDataStore("CurrencyStore")
local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(Player)
	local UserId = Player.UserId
	local Currency = CurrencyStore:GetAsync(UserId)
	
	if Currency == nil then
		Currency = 0
		CurrencyStore:SetAsync(UserId, Currency)
	end
	
	local Leaderstats = Instance.new("Folder", Player)
	Leaderstats.Name = "leaderstats"
	
	local Tokens = Instance.new("IntValue", Leaderstats)
	Tokens.Name = "Tokens"
	
	Tokens.Value = Currency
	
	Tokens.Changed:Connect(function(NewValue)
		CurrencyStore:SetAsync(UserId, NewValue)
	end)
end)

The script that is erroring:

game.ReplicatedStorage.GivePlayerItem.OnServerEvent:Connect(function(Player, PlayerName)
	local ToolToGive = Player.Character:FindFirstChildWhichIsA("Tool")
	ToolToGive.Parent = game.Players[PlayerName].Backpack
	local Tokens = Player.leaderstats.Tokens
	Tokens.Value = Tokens.Value + 1
end)

How do I fix this?

1 Like

Where are the scripts located, and which type of scripts are they?
Print Player and PlayerName and check if they’re valid
Print along the script to see where it fails
Print Player.leaderstats:FindFirstChild(“Tokens”) right after the Instance to check if it was added successfully

Just a tip, you can actually do

local Currency = CurrencyStore:GetAsync(UserId) or 0 -- if no "Currency" then assign it to 0

instead of

local Currency = CurrencyStore:GetAsync(UserId)
	
if Currency == nil then
	Currency = 0
end

And you can also do Tokens.Value += 1 instead of Tokens.Value = Tokens.Value + 1

1 Like

ServerScripts both located in ServerScriptService.

I’d suggest making a print function straight after you create the Tokens value, and ensuring that it exists by printing the player’s tokens. If it does print, then it’s probably because the remote event is firing before the tokens are actually created, which can be fixed by changing this (replicated storage):

local Tokens = Player.leaderstats.Tokens

To this:

local Tokens = Player.leaderstats:WaitForChild("Tokens")

Can you show the script that fires the remote event?

1 Like

There is no remote event though.

18:11:36.320 - Infinite yield possible on ‘Players.NotAid_n.leaderstats:WaitForChild(“Tokens”)’

18:11:36.322 - Stack Begin

18:11:36.323 - Script ‘ServerScriptService.GivePlayerItem’, Line 4

18:11:36.325 - Stack End