Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

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)

This discussion is preserved as it was. New answers, comments, and votes are closed.