I can’t find out why this happens;
the longer my script runs, the laggier it gets, and after collecting a coin the lag stops and slowly comes back??
Video: (Look at the frame time graph)
Scripts:
Collect Script in ServerScriptService
respawnTime = 3 -- How long the coin takes to reappear.
waitTime = 0.1 -- How long to wait.
range = 5 -- Pickup range in studs.
coinLocation = workspace.Coins -- Coin Location
debugg = true
repStorage = game:GetService("ReplicatedStorage")
players = game:GetService("Players")
while wait(waitTime) do -- Check distance of each player to each coin.
allCoins = workspace.Coins:GetChildren()
for i,v in ipairs(allCoins) do
pos1 = v.Position
for _, player in pairs(players:GetPlayers()) do
DistanceToObject = player:DistanceFromCharacter(pos1)
if DistanceToObject == nil or DistanceToObject == 0 then
warn("pos2 == nil")
break -- Avoid erroring
end
if DistanceToObject < range and v.Collectable.Value == true then
print(v, "collected!")
repStorage.coinDisappear:FireAllClients(v)
v.Collectable.Value = false
end
------------------------------------------------------------------------------
if debugg == true then
if DistanceToObject > range then
warn("DistanceToObject isn't within range",range)
elseif v.Collectable.Value == false then
warn("Collectable Value of",v,"is false")
end
end
------------------------------------------------------------------------------
end
end
end
Client Side Script
-- I removed some parts of the code to reduce clutter
RepStorage = game:GetService("ReplicatedStorage")
TweenService = game:GetService("TweenService")
Players = game:GetService("Players")
PopupUI = script.Parent:WaitForChild("PopupGUI") -- The Billboard GUI
CoinAmountText = PopupUI:WaitForChild("CoinFrame"):WaitForChild("AmountText") -- Coin Text inside of it
RootPart = Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")
leaderstats = script.Parent.Parent.leaderstats -- Your leaderstats
FadeTime = 0.5
DisplayTime = 5
oldVal = 0
RepStorage.coinDisappear.OnClientEvent:Connect(function(v) -- Fade out coin
local coin = workspace.Coins:FindFirstChild(tostring(v))
print(coin)
TweenService:Create(coin, TweenInfo.new(FadeTime), {Transparency = 1, Size = Vector3.new(4.5, 0.54, 4.5)}):Play()
end)
RepStorage.coinShow.OnClientEvent:Connect(function(v) -- Fade in coin
local coin = workspace.Coins:FindFirstChild(tostring(v))
coin.Size = Vector3.new(2.5, 0.3, 2.5)
TweenService:Create(coin, TweenInfo.new(FadeTime), {Transparency = 0}):Play()
end)
Edit: I rewrote the entire thing, and it seems to be working now!