local part = script.Parent part.Touched:Connect(function(H) local plr = H.Parent local EXP = plr:FindFirstChild("Leaderstats").Experience EXP.Value = EXP.Value + 20 end)
so here is the script, i don't know what im doing wrong
12:31:10.691 - Workspace.Part.Script:6: attempt to index a nil value
this is the error i get
local Players = game:GetService("Players") Script.Parent.Touched:Connect(function(Hit) local Player = Players:GetPlayerFromCharacter(Hit.Parent) if Player then local Exp = Player.leaderstats.Experience Exp.Value = Exp.Value + 20 end end)
You have 2 problems in here, the first one is that you have to verify first that the object that touched the part is a player/character, second is that you misspelled leaderstats
. I knew this because to make a leaderboard you need to make a folder or something that is called leaderstats
inside the player and that Leaderstats
won't work.
I'll explain how I verified that the object that touched the part is a character.
local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
By using :GetPlayerFromCharacter()
you can get the player, but if the object you put -->()
<-- here is not a character it then gives you nil.
So if it's not a character the code above is the same as this :
local Player = nil
, nil basically means nothing or doesn't exist.
if Player then local Exp = Player.leaderstats.Experience Exp.Value = Exp.Value + 20 end
if Player then
check's if the Player
is true, so it's the same as this :
if Player ~= nil then
, ~=
means "is not equal to", the opposite of ==
which means "is equal to".
Now, if the player is not nil or true then it would run the following code :
local Exp = Player.leaderstats.Experience Exp.Value = Exp.Value + 20
You now know this won't give any errors because you know, that player exists, Remember the error?
12:31:10.691 - Workspace.Part.Script:6: attempt to index a nil value
12:31:10.691
is the time which the error happened.
Worspace.Part.Script
is the script that caused the error.
:6:
is the line in the script which caused the error.
attempt to index a nil value
this means that you tried to index a nil value, or in other words, you tried to do something to something that doesn't exist or nil.
You have to make sure that a player activated the hit function as anything that touches the part will activate the fuction. Because every player has a humanoid in them, you can check if a player triggered the function bu asking:
if H:FindFirstChild("Humanoid") then