Hello there I have a problem with a touch it should take the backpack value and add it to the leaderstats Value and then comes the error in the console how do I fix that here is my script:
local toggle = 10 script.Parent.Parent.Touched:Connect(function(hit) if toggle == 10 then toggle = 0 local playern = hit.Parent.Name local Player = game.Players:FindFirstChild(playern) print("found") local Save = Player.BackpackFill.Value Player.leaderstats.Tea.Value = Save Player.BackpackFill.Value = 0 wait(2) toggle = 10 end end)
Hello, Lazytfft12.
I believe the problem is, your script is not checking if the (hit) has a Parent or a Humanoid.
I have edited your script.
local toggle = 10 script.Parent.Parent.Touched:Connect(function(hit) if toggle == 10 then if hit.Parent and hit.Parent:FindFirstChild("Humanoid") or hit.Parent.Parent:FindFirstChild("Humanoid") then toggle = 0 local playern = hit.Parent.Name local playern2 = hit.Parent.Parent.Name if game.Players:FindFirstChild(playern) or game.Players:FindFirstChild(playern2) then print("Player Detected") local Save = Player.BackpackFill.Value Player.leaderstats.Tea.Value = Save Player.BackpackFill.Value = 0 wait(2) toggle = 10 else print("No Player Found") return end else return end end wait(0.5) end)
The reason for this is because when FindFirstChild
cannot find an object with the name specified, it will return nil
. This is what happened in your case, since an object with the name hit.Parent.Name
was not found. You need a check to see if the player exists
local toggle = 10 script.Parent.Parent.Touched:Connect(function(hit) if toggle == 10 then toggle = 0 local char = hit.Parent local Player = game.Players:GetPlayerFromCharacter(char) if Player then -- Checking if it was an actual player. print("found") local Save = Player.BackpackFill.Value Player.leaderstats.Tea.Value = Save Player.BackpackFill.Value = 0 wait(2) toggle = 10 end end end)
As you can see I used a different method of getting the player. I used GetPlayerFromCharacter
. It takes a model as an argument. If a player's character is the model passed, it will return the player from that character. It's a bit more reliable than FindFirstChild.