✓ Accepted answer
First let me clean up the code you have quick:
local tool = script.Parent
local handle = tool.Handle
local player = script.Parent.Parent.Parent
function onActivate()
handle.Touched:Connect(function(otherPart)
if otherPart.Name == "Wood" then
workspace.woodCount.Value = workspace.woodCount.Value + 1
player.PlayerGui.wood.TextLabel.Text = workspace.woodCount.Value
else
print("Not wood");
end
end)
end
tool.Activated:Connect(onActivate)
And now just an explanation for the current behavior:
What you have now will: a) when the user clicks, create a new function and b) set up the newly created function to run every time the Handle is touched by something.
So if you don't click at all, the value will never be incremented.
If you click once, nothing will happen until you touch a brick, in which case value will increase by 1.
If you click twice, nothing will happen until you touch a brick, in which case value will increase by 2 because two functions will run.
The fix
You have a few options. Maybe one of the easiest to understand would be to just disconnect the Touched event after a period of time, like this:
local tool = script.Parent
local handle = tool.Handle
local player = script.Parent.Parent.Parent
local waitTime = 0.3
local connection;
function onActivate()
if (connection) then
connection:disconnect()
connection = nil
end
connection = handle.Touched:Connect(function(otherPart)
if otherPart.Name == "Wood" then
workspace.woodCount.Value = workspace.woodCount.Value + 1
player.PlayerGui.wood.TextLabel.Text = workspace.woodCount.Value
connection:disconnect()
connection = nil
else
print("Not wood");
end
end)
wait(waitTime)
if (connection) then
connection:disconnect()
connection = nil
end
end
tool.Activated:Connect(onActivate)
Another way (which I personally think is better) would be to always listen for the .Touched event, and have the .Activated event control whether or not it does anything:
local tool = script.Parent
local handle = tool.Handle
local player = script.Parent.Parent.Parent
local waitTime = 0.3
local canIncrease = false
handle.Touched:connect(function(otherPart)
if (not canIncrease) then return end
if (otherPart.Name == "Wood") then
workspace.woodCount.Value = workspace.woodCount.Value + 1
player.PlayerGui.wood.TextLabel.Text = workspace.woodCount.Value
canIncrease = false
end
end)
tool.Activated:connect(function()
canIncrease = true
wait(waitTime)
canIncrease = false
end)
Note that this will probably have some strange behavior if you click multiple times very rapidly. I'll leave it as an exercise for you to figure out how to fix that, if you're feeling like it needs to be fixed.
1 comment
Wow, thanks for the detailed response. I definitely learnt from this! :)