Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Workspace.CupGiver.Script:9: attempt to index local 'plr' (a nil value)?

Asked by
OldBo5 30
5 years ago

My code is:

script.Parent.Touched:Connect(function(hit)
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
local cup = game.ReplicatedStorage:WaitForChild("Cup")
local debounce = false
if debounce == false then
    debounce = true
    script.Parent.Parent = game.ReplicatedStorage
end
cup:Clone().Parent = plr.Backpack
if debounce == true then
    wait(5)
    debounce = false
    game.ReplicatedStorage.CupGiver.Parent = workspace
end
end)

1 answer

Log in to vote
0
Answered by
Amiaa16 3227 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

You need to check if GetPlayerFromCharacter() doesn't return nil, as hit.Parent may not always be the character model but i.e. an accessory or a random part completly unrelated to any player.

Also you need to move your debounce declaration outside of the anonymous function.

local debounce = false

script.Parent.Touched:Connect(function(hit)
    if debounce then
        return --abort if debounce is active
    end
    debounce = true
    local plr = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
    if not plr then
        return --abort if plr is nil
    end
    local cup = game:GetService("ReplicatedStorage"):WaitForChild("Cup")
    cup:Clone().Parent = plr.Backpack
    --here you can set its transparency to 1 or something but you shouldn't reparent it each time
    wait(5)
    debouce = false
    --and here you can set transparency back to 0
end)
Ad

Answer this question