I am removing parts as they are collected by a Player.
The character walk lags when I pick up the first part, but none of the parts afterwards will cause a lag spike.
It only happens if the character is walking while picking up the part.
Makes no sense I can figure.
Does anyone else see this happening?
Here is the code that removes the part:
local Part = script.Parent
local CanTouch = true
Part.Touched:Connect(function(OtherPart)
if CanTouch == false then return end
if not OtherPart then return end
if not OtherPart.Parent:FindFirstChild("HumanoidRootPart") then return end
CanTouch = false
game.Debris:AddItem(script.Parent, 0.1)
end)
I think that the lag happens because the Touched event keeps firing repeatedly when the character moves over the part. To fix this, I provided you an updated version of the code, adding a small cooldown between each touch
local Part = script.Parent
local CanTouch = true
Part.Touched:Connect(function(OtherPart)
if CanTouch == false then return end
if not OtherPart then return end
if not OtherPart.Parent:FindFirstChild("HumanoidRootPart") then return end
CanTouch = false
game.Debris:AddItem(script.Parent, 0.1)
task.wait(0.2)
CanTouch = true
end)
No real need to add a debounce if the event is not to be fired again. Just disconnect it, or set BasePart.CanTouch to false and let the deletion of the script handle the rest.
There is also no need to wait 0.1 seconds to delete the part, @mc7oof
Alright, thanks for the clarification, but I was also thinking that if the lag only happens with the first part pickup, it could be related to how the event is handled for the initial touch. You can try disconnecting the Touched event after the first trigger, so it won’t be called again, and ensure the part is removed immediately without any delay using game.Debris:AddItem(Part, 0)
local Part = script.Parent
local CanTouch = true
Part.Touched:Connect(function(OtherPart)
if not CanTouch then return end
if not OtherPart then return end
if not OtherPart.Parent:FindFirstChild("HumanoidRootPart") then return end
CanTouch = false
Part.Touched:Disconnect()
game.Debris:AddItem(Part, 0)
end)
That is not an available solution. You need to verify the collision was with a player first, otherwise a tumbleweed could take the coin and prevent further interaction
I would first confirm whether or not the deletion of the script prevents multiple responses from player collision. If it doesn’t, then disconnecting the event or disabling CanTouch (the property, not as a debounce) will suffice
What sort of lag is occurring exactly? This sort of feature should be implemented on the client VFX-wise. The player will collide with the part and notify the server. The server will verify the client is within a specific radius of the part before awarding them. The part does not need to exist on the server; the client will delete the part regardless of whether or not they’re rewarded. They’ll also delete the part if other clients collide with it first