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?
First, the plr
argument can only be used in the function, place all the codes inside the PlayerAdded
function and it would fix the error. Secondly, the if statement will only be checked once, use :GetPropertyChangedSignal()
or .Changed
to fire a function and check if the value reaches 30 or higher. The code should be like this.
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" local clickDetector = game.Workspace.Button.ClickDetector clickDetector.MouseClick:Connect(function(plr) plr.leaderstats.Points.Value = plr.leaderstats.Points.Value + 1 end) plr.leaderstats.Points.Value:GetPropertyChangedSignal("Value"):Connect(function() if plr.leaderstats.Points.Value >= 30 then game.Workspace.Barrier.BrickColor = BrickColor.new("Lime green") game.Workspace.Barrier.CanCollide = false end end) end)