I want the player to be able to sell their inventory. However, when selling a ton of items at once, The game lags like CRAP.
Here’s my script:
script.Parent.Triggered:Connect(function(plr)
local counter = 0
for i, v in pairs(plr.Backpack:GetChildren()) do
counter += 1
if v:FindFirstChild("value") then
local value = v.value.Value
v:Destroy()
plr.leaderstats.Cash.Value += value
end
if counter == 25 then
counter = 0
wait(0.1)
end
end
end)
I thought selling 25 items in bulk and then giving the script a 0.1 second break (to avoid taking literally a billion years to sell everything) would reduce lag, and while it did just a tiny bit, it is still VERY laggy as you can see in this video:
So this would mean I would have to get the values first, add them up, give the player their money, and THEN get rid of all the children? (this is a question, just confirming)
The microprofiler can tell you exactly what’s causing the lag, you know that a lag spike occurs when you interact with it, but you don’t know what exactly causes it.
Here’s the result:
The orange and yellow is the script trying to destroy everything in your inventory, finding the value of the tool and changing your leaderstats. This seems like a problem, as it is mainly the destruction that makes up the orange bar.
Add a task,wait() after destroying every object. Another thing you can do is remove it from the player’s inventory so it doesn’t show and delete it in the background gradually with task.wait()
This is unfortunately ALL necessary for saving inventories in DataStores the way I’m doing it. This way of saving causes no lag and is actually PRETTY efficient.