What's the problem with this script? I am working on a Pokemon game an I need to make collectible items. This is the script for the rock item that is supposed to add 1 additional rock when clicked. The middle is not really important, I think. It works fine if I replace "function onClicked(part)" with "function onTouched(part)" and "script.Parent.ClickDetector.MouseClick:connect(onClicked)" with "script.Parent.Touched:connect(onTouched)", but that's not what I want to do with the script. I can provide more information if needed. Yes, I put ClickDetector inside the part. Thanks.
local amnt = 1 function onClicked(part) local h = part.Parent:findFirstChild("Humanoid") if (h~=nil) then local thisplr = game.Players:findFirstChild(h.Parent.Name) if (thisplr~=nil) then local stats = thisplr:findFirstChild("stats") if (stats~=nil) then local score = stats:findFirstChild("Rock") if (score~=nil) then score.Value = score.Value + amnt end end end script.Parent:remove() end end script.Parent.ClickDetector.MouseClick:connect(onClicked)
The MouseClick event has a parameter
that shows which player
clicked the button. With that being said, you can get rid of the first few lines and edit the stats variable line to point to the player.
local amnt = 1 function onClicked(plr) --Changing the variable name so we know it's the player. local stats = plr:findFirstChild("stats") if stats then --More efficient way of finding if stats is available. local score = stats:findFirstChild("Rock") if score then score.Value = score.Value + amnt end end script.Parent:remove() end script.Parent.ClickDetector.MouseClick:connect(onClicked)
Also, you can use a debounce
variable to make sure the player gets one rock and one rock only.
local amnt = 1 local db = false function onClicked(plr) --Changing the variable name so we know it's the player. if db then return end --If the db variable is true, stop the function. db = true --Set the variable to true so other instances of the function don't fire. local stats = plr:findFirstChild("stats") if stats then --More efficient way of finding if stats is available. local score = stats:findFirstChild("Rock") if score then score.Value = score.Value + amnt end end script.Parent:remove() end --Usually, you'd set db to false to allow other instances of the function to run, but since the script is being deleted (as you're removing it's parent), there's not need to do this. script.Parent.ClickDetector.MouseClick:connect(onClicked)
If this helped, please upvote and accept my answer. :)
Further reading: