Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

My script isn't finding the leaderboard, any answers?

So I have been working on this for a while but I can't figure out how to get it to work without the erroring out.

here is the script that sets up a leaderboard:

local function onPlayerJoin(player)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Value = 10
	cash.Parent =  leaderstats
	
end

game.Players.PlayerAdded:Connect(onPlayerJoin)

that script works perfectly fine and the leaderboard works as intended, but when whatever I do here does not work, it always errors out saying:

attempt to index nil with 'leaderstats'

these are two different scripts btw

local Players = game:GetService("Players")
 
local function onCharacterAdded(character)
	
	local cash = character.leaderstats.Cash.Value -- THIS is the line that is showing the error
	return cash
	
end
 
local function onPlayerAdded(player)
	player.CharacterAdded:Connect(onCharacterAdded)

end
 
Players.PlayerAdded:Connect(onPlayerAdded)

local cash =  onCharacterAdded()

if you have any ideas on how I could fix this let me know

1 comment

0

Thats because you are referencing the parameter character to leaderstats make sure you referenced userdata like game.Workspace.leaderstats.Cash.Value

2 answers

Im not sure what the problem is but this is the script i use to make the leaderboard and i put it in the workspace

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

local folder = Instance.new("Folder", plr)
folder.Name = "leaderstats"

local coins = Instance.new("IntValue", folder)
coins.name = "Coins"
end)

Improvements

Rather than having local functions, characterAdded can be nested under playerAdded

Use WaitForChild to make sure an instance exists before using it

Issues

Your initial script places the leaderstats under the instance of the player, not their character. This folder is not moved to the Character when the player's character is added to the game.

Revised Server Script

local Players = game:GetService("Players")
local cash = 10

Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		cash = player:WaitForChild("leaderstats"):WaitForChild("Cash").Value
	end)
end)

If you wanted to keep the local functions, just change line 5 to

local cash = Players:GetPlayerFromCharacter(character):WaitForChild("leaderstats"):WaitForChild("Cash").Value

This discussion is preserved as it was. New answers, comments, and votes are closed.