I am writing a script where if you press a button a certain amount of time, a closed barrier will open.
This is the script I wrote:
game.Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder")
leaderstats.Parent = plr
leaderstats.Name = "leaderstats"
local Points = Instance.new("IntValue", leaderstats)
Points.Name = "Points" -- Code for the leaderstat.
end)
local clickDetector = game.Workspace.Button.ClickDetector
clickDetector.MouseClick:Connect(function(plr)
plr.leaderstats.Points.Value = plr.leaderstats.Points.Value + 1 -- Adds a point every time the player clicks the button.
end)
if plr.leaderstats.Points.Value >= 30 then
game.Workspace.Barrier.BrickColor = BrickColor.new("Lime green")
game.Workspace.Barrier.CanCollide = false
end -- I want this to run if the players' points are greater than or equal to 30, only gave me an error.
I put the code above inside a normal script at ServerScriptService. Whenever I playtest the game this error appears: 16:16:57.032 - ServerScriptService.Leaderstats:16: attempt to index nil with 'leaderstats'. I was expecting that the barrier will open once the player has 30+ points...
The code runs perfectly fine and adds one point every time I click the button... until it reaches line 16. The error told me that there's something wrong with it. I do not know what part of it I did a mistake or if I used a wrong syntax.
I tried doing this and this one, doesn't work or am I missing something?

2 comments
That is because you haven't declared the 'plr' variable outside the MouseClick Event. plr will only work inside the event (not outside)
Use while true do, If the player doesn't have the amount of points the script won't run. Once it runs that would be the end of it but if you used while true do, as soon as you get 30 points it will open. Also a sidenote for using while true do, do while true do wait(). If you just do while true do then it will crash the game