local Coin = script.Parent
local CoinTouched = false
Coin.Touched:Connect(function(hit)
local HRP = hit.Parent:FindFirstChild('HumanoidRootPart')
if HRP then
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
local leaderstats = plr:FindFirstChild('leaderstats')
local CoinsStat = leaderstats.Coins
CoinTouched = true
CoinsStat.Value += 10
Coin:Destroy()
end
end)
The code works the way it is suppose to work, however when it gets to the Coin:Destroy() part it lags my game out for half a second. I know this because I replaced that line with Script.Enable = false and the lag didn’t seem to occur anymore. Does anyone know why this happens, and if possible give me a solution to this issue?
What effect? Could that be the source of the issue? Deleting a union should be relatively cheap and something you shouldn’t notice if you are deleting one at a time.
Honestly I’m out of ideas as to why this could be happening. I have a few questions that might help, but I kind of doubt they will.
Does your game lag out if you just remove the destroy line without disabling the script?
Also what if you delete the coin from another script after a couple seconds without triggering touch?
What if you replace the coin with a single part?
As for a potential workaround you can try object pooling. Never delete the coin but carefully manage a collection of them and just set them up and deconstruct the script stuff as you go.
found the problem, it’s that your placing your script into the coin. Place it in serverscriptstorage and test if it works. If it does (which it did in my case) Use collection service so you can use the code on more then one coin
Heres the code
local CollectionService = game:GetService("CollectionService")
local Tag = "Coin"
local function Coin(CoinModel)
Coin.Touched:Connect(function(hit)
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if not plr then return end
Coin:Destroy()
end)
end
CollectionService:GetInstanceAddedSignal(Tag):Connect(Coin)
for i,v in ipairs(CollectionService:GetTagged(Tag)) do
Coin(v)
end