Why does this only work when I walk into it not when I click it? It is supposed to give you a cup when you click but it doesn’t. it only gives you a cup when you walk into the selection box area.
script.Parent.Touched:Connect(function(hit)
if hit.Parent:IsA("Model") and DB == false then
DB = true
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
local cup = game.ServerStorage:WaitForChild("Drinks"):WaitForChild("Cup"):Clone()
cup.Parent = plr:WaitForChild("Backpack")
wait(3)
DB = false
end
end)```
Images:
https://gyazo.com/36cb2d5af68a70114b26fba74dc1afcb
If you are looking to detect when a part is clicked, a ClickDetector is a good option. The .Touched event is only used for physical collisions, so it won’t register mouse clicks of any kind.
Once you place a ClickDetector as a child of a BasePart, you can detect clicks like so:
local DB = false
ClickDetector.MouseClick:Connect(function(PlayerWhoClicked)
if hit.Parent:IsA("Model") and DB == false then
DB = true
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
local cup = game.ServerStorage:WaitForChild("Drinks"):WaitForChild("Cup"):Clone()
cup.Parent = plr:WaitForChild("Backpack")
wait(3)
DB = false
end
end
You need to use the Player argument from the ClickDetector, instead of trying to generate it from a hit.
local DB = false
ClickDetector.MouseClick:Connect(function(PlayerWhoClicked)
if DB == false then
DB = true
local plr = PlayerWhoClicked
local cup = game.ServerStorage:WaitForChild("Drinks"):WaitForChild("Cup"):Clone()
cup.Parent = plr:WaitForChild("Backpack")
wait(3)
DB = false
end
end
Also, are you sure you have created the ClickDetector instance?
local DB = false
local clickDetector = script.Parent.ClickDetector
clickDetector.MouseClick:Connect(function(PlayerWhoClicked)
if DB == false then
DB = true
local plr = PlayerWhoClicked
local cup = game.ServerStorage:WaitForChild("Drinks"):WaitForChild("Cup"):Clone()
cup.Parent = plr:WaitForChild("Backpack")
wait(3)
DB = false
end
end
There is an object that needs to be created as a child of a part which is the click detector Instance as seen in the image below for the click detector to work:
I recommend reading the dev forum API that @ExcessEnergy linked on the click detector or by watching a video tutorial such as PeasFactory which I have linked below at this timestamp: