How would I make a Coin Render Distance?

I’m trying to improve my coin system as it causes lag, how would I check a distance around the player to spawn the coins in? It’s really difficult for me to figure out a solution:

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

is this a module script?

chsar limit

yep, it’s a module script. Main problems consist of it having to manage all the coins, so why not do the coins in a area of a range maybe. Or it could be called from a client. I’m not sure.

Maybe you could add an if statement where it gets the NewCoin’s position and it gets the .Magnitude of it between the Coin and the player.

So overall, something like this:

local Distance = (NewCoin.Position - player:WaitForChild("HumanoidRootPart").Position).Magnitude
2 Likes