If statements and RunService.Renderstepped

Hi!
I have a script where a part follows the mouse pointer when a tool is equipped.
There is a limit so that the part stops when it is 50 studs away from the player.

I want the part to turn red when it is 30+ studs away from the player.

My question though, is if I were to script this, would it be damaging to game performance if I had an If statement in the script to detect if the part was over 30 studs away, and then change the colour?

If so, how would I do this more efficiently?

SCRIPT:

local tool = script.Parent
local player = game.Players.LocalPlayer
local mouse = game.Players.LocalPlayer:GetMouse()


tool.Equipped:Connect(function()
	print("equipped")
	
	local cursorPart = script.Parent.CursorPart
	local cursorPart = script.Parent.CursorPart
	local hrp = player.Character.HumanoidRootPart
	
	game:GetService('RunService').RenderStepped:Connect(function()
		local pos = mouse.Hit.Position
		cursorPart.CFrame = CFrame.new(pos) * CFrame.new(0,math.floor,0)
		
		local range = math.min(50, (hrp.Position - pos).Magnitude)
		local direction = (pos - hrp.Position).Unit
		cursorPart.CFrame = CFrame.new(hrp.Position + direction * range)
	end)
	
end)

tool.Unequipped:Connect(function()
	print("unequipped")
end)

A simple if statement wouldn’t damage performance, but the one damaging performance is RenderStepped itself and what you change in it. Every time the tool is equipped you are creating a new RenderStepped causing it to stack over time. When the tool is unequipped, I recommend disconnecting it:

local render
...
render = game:GetService('RunService').RenderStepped:Connect(function()
....
tool.Unequipped:Connect(function()
print("unequipped")
if render then
render:Disconnect()
end
end) 
1 Like

Yep, thanks for that! That was gonna be the next thing I did :slight_smile: But again, thanks for the input.