Is there a way to make this more efficent?

I created this script for a custom proximity prompt sorta thing yesterday but it causes lag spikes and frame drops. I think it may have something to do with the for loop, but I’m not entirely sure.

assigning all of the prompts to a table:

for i, v in pairs(game.Workspace:GetDescendants()) do
	if v.Name == "Prompt" then
		table.insert(prompts, v)
	end
end

main code:

while true do
	local refrencedPrompt = PromptModule.FindClosestPrompt(player.Character, prompts)
	
	PromptModule.CheckShowPrompt(player, refrencedPrompt)
	
	for i, v in ipairs(prompts) do
		if v == refrencedPrompt then
		else
			v.Enabled = false

			if v.Parent:FindFirstChild("PromptBack") then
				v.Parent:FindFirstChild("PromptBack").Enabled = false
			end

			v.Parent.Beam.Attachment0 = nil
		end
	end
	
	local magnitude = (player.Character.HumanoidRootPart.Position - refrencedPrompt.Parent.Position).Magnitude
	
	if magnitude <= refrencedPrompt.Parent.Settings.MaxDistance.Value then
		promptShown = refrencedPrompt
		
	else
		promptShown = nil
	end
	
	wait()
end

the module script works really well and i wont get into why it isnt here

while wait() do
	local Magnitude = (Player.Character.HumanoidRootPart.Position - RefrencedPrompt.Parent.Position).Magnitude
	local RefrencedPrompt = PromptModule.FindClosestPrompt(Player.Character, Prompts)
	PromptModule.CheckShowPrompt(Player, RefrencedPrompt)
	
	for i, v in ipairs(Prompts) do
		if v == RefrencedPrompt then
		else
			v.Enabled = false
			if v.Parent:FindFirstChild("PromptBack") then
				v.Parent:FindFirstChild("PromptBack").Enabled = false
			end
			v.Parent.Beam.Attachment0 = nil
		end
	end

	if Magnitude <= RefrencedPrompt.Parent.Settings.MaxDistance.Value then
		PromptShown = RefrencedPrompt
	else
		PromptShown = nil
	end
end

Is there an alternative to continuously checking the position or is there a way to update it when the player moves?

I’m not too sure, sorry! (char lim)

1 Like

Maybe one of these would help

The articles help a lot, I will get one of my testers to see if it is less laggy

1 Like

No problems, if it helped you, please make it as a solution :slight_smile:

Good luck!