This script works in the sense that it makes all the right instances, but when I change the value of EXP to, say, 100, my player doesn't level up to level 2.
game.Players.PlayerAdded:connect(function(plr) local stats = Instance.new('IntValue', plr) stats.Name = 'leaderstats' experience = Instance.new('IntValue', stats) experience.Name = 'EXP' experience.Value = 0 level = Instance.new('IntValue',stats) level.Name = 'Level' level.Value = 0 end) function level() local required=(level.Value*100) if experience.Value>=required then level.Value=level.Value+1 experience.Value=experience.Value-required level() wait(.01) end end experience.Changed:connect(level)
I get the error Workspace.Script:22: attempt to index global 'experience' (a nil value) This means that somewhere on line 22 I went wrong. I don't see how, because experience is defined correctly and the fuction's name is level. Any help is appreciated, thank you for reading.
Simple answer.The variable for the connection line in line has to be difined globally. To fix this, you'd put the level()
function within the (function(plyr)
. It would look something like this:
game.Players.PlayerAdded:connect(function(plr) local stats = Instance.new('IntValue', plr) stats.Name = 'leaderstats' experience = Instance.new('IntValue', stats) experience.Name = 'EXP' experience.Value = 0 level = Instance.new('IntValue',stats) level.Name = 'Level' level.Value = 0 experience.Changed:connect(function() level() function level() local required=(level.Value*100) if experience.Value>=required then level.Value=level.Value+1 experience.Value=experience.Value-required wait(.01) level() end end end) end)
I would try getting the Value inside the player with a separate variable (Outside of the player added event). You may do this by looping through each player and checking to see if it has changed. Or if it's not a server script then don't use the loop and use local player instead!
for _, player in pairs (game.Players:GetChildren()) do local Stats = player:FindFirstChild'leaderstats' if Stats then local Experience = Stats:FindFirstChild'EXP' if Experience then Experience.Changed:connect(level) end end end
OR if not a server script.
local player = game:GetService'Players'.LocalPlayer local Stats = player:FindFirstChild'leaderstats' if Stats then local Experience = Stats:FindFirstChild'EXP' if Experience then Experience.Changed:connect(level) end end
ProTip: If you are adding values to a player then I would use the starter player service for that. Anything inside that will be copied to the player when they join.
Hope this helps! ;)