I have been working on my game and each time I test it in studio it is absolutely fine, but as soon as I play in the normal game and hit something using the .Touched Event it makes the entire game lag enormously and the ms keeps rising by 200-1000 every second. I think this is caused by the .Touched event from what I've seen.
Is there possibly another way to make the .Touched event not lag / slow down? If so, how?
Thank you in advance.
use debounce:
Wait's 5 seconds before you can use it again
local debounce = false function Touch(Event) if debounce == false then debounce = true -- script u want here wait(5) debounce = false end end script.Parent.Touched:Connect(Touch)
Debounce is a commonly used feature which makes the script wait a certain amount of timew which can then fire your code;
If we use the most commonly used; "Touched Event Line", and add debounce you will realise it does not lag.
local PartName = "Part" local db = false workspace[PartName].Touched:Connect(function() if not db then db = true print("I was touched") wait(5) db = false end end)
This will wait five seconds before firing the same action;
If you go in the dev-console; F9, then go to memory and press UntrackedMemory. UntrackedMemory, can cause a lot of lag, and many developers suffer from it
This is a scale from worst to least;
1 - Connections 2 - While Loops 3 - Other repetitive stuff 4 - 5 - 6 -
Connections;
script.Parent.Touched:Connect(function() print("Hi") end)
Loops;
while true do wait() print("HI")
Every-time a connection occurs, it goes directly into the UntrackedMemory folder.
Connections;
script.Parent.Touched:Connect(function() print("Hi") script.Parent.Touched:Disconnect()
Loops;
while true do wait() print("Hello") break