My coin system may be the source of the lag as it contains a lot of problems. For starters, it tries to handle every player collecting coins and generates them even if millions of studs away. Im unsure how to approach this laggy code:
local Coin = {}
local Debris = game:GetService("Debris")
local TweenService = game:GetService("TweenService")
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Tokens = workspace:FindFirstChild("Tokens")
local CoinFolder = ServerStorage:FindFirstChild("Coins")
local CollectionService = game:GetService("CollectionService")
local LS = nil
Coin.CoinTaken = function(player, CoinType, TheCoin, state)
if not state then
state = true
local Amount = 0
local PlayerToFind = Players:GetPlayerFromCharacter(player.Parent)
if not PlayerToFind then return end
LS = PlayerToFind:FindFirstChild("leaderstats")
if TheCoin and TheCoin:FindFirstChild("Amount") and LS then
if MarketplaceService:UserOwnsGamePassAsync(PlayerToFind.UserId, 147063459) then
LS.Tokens.Value += TheCoin.Amount.Value * 2
else
LS.Tokens.Value += TheCoin.Amount.Value
end
end
Amount = 5
if TheCoin:FindFirstChild("Timer") then
Amount = TheCoin.Timer.Value
end
local PreviousPos = TheCoin.Position
TheCoin:Destroy()
-- WAIT 5 seconds to spawn that coin again
task.delay(Amount, function()
Coin.New(PreviousPos, CoinType)
state = true
end)
end
end
Coin.New = function(position, Type)
local desiredCoin = CoinFolder:FindFirstChild(Type)
local NewCoin = desiredCoin:Clone()
CollectionService:AddTag(NewCoin, "Coin")
NewCoin.Parent = Tokens
NewCoin.Position = position
NewCoin.Touched:Connect(function(player)
Coin.CoinTaken(player, Type, NewCoin, false)
end)
end
return Coin
ideas i have are:
would it be possible to make it client sided to reduce even more lag?
would it be possible to give it a distance range then?
its really confusing on how to start making this script less laggy.