Can this loop cause lag?

[Sorry i had to rewrite my code and repost this. I noticed that i had made some typos in the script]

I’m not really sure if this can or will cause nay lag?

  1. What is the issue? Include screenshots / videos if possible!

Like i said. I’m not really sure if this pice of code can cause any lag in the game. I don’t want to have anything that can cause lag for obvious reasons.

This is the code i have inside my script. The script is parented to a Part:

repeat wait(4) until #game.Players:GetPlayers() > 0



local Root = script.Parent


function getTarget(Target)	
	local Target = 0
	local Dist = 50


	for _, v in pairs(game.Players:GetPlayers()) do
		local PHumanoid = v.Character:FindFirstChild("Humanoid", 4)
		local PTorso = v.Character:FindFirstChild("HumanoidRootPart", 4)
		if PHumanoid.Health > 0 and PTorso then
			if (Root.Position - PTorso.Position).Magnitude <= Dist then
				Target = PTorso
			end
		end
	end


	return Target
end

function Sight(Target)
	print(Target)
	local Rayparams = RaycastParams.new()
	Rayparams.FilterType = Enum.RaycastFilterType.Blacklist
	Rayparams.FilterDescendantsInstances = {script.Parent}

	local Rayresult = game.Workspace:Raycast(Root.Position, (Target.Position - Root.Position).Unit * 100, Rayparams)
	if Rayresult ~= nil then
		if Rayresult.Instance:IsDescendantOf(Target.Parent) then
			return true
		else
			return false
		end
	end
end

	
while true do
	local Target = getTarget()
	if Target then
		local canSee = Sight(Target)
		if canSee == true then
			Root.CFrame = CFrame.new(Root.Position, Target.Position)
		end
	end
	wait()
end

Any help would be appreciated :slightly_smiling_face: :slightly_smiling_face:!!

2 Likes

to prevent it from lagging, after “for _, v in pairs(game.Players:GetPlayers()) do” put a wait like:
for _, v in pairs(game.Players:GetPlayers()) do
wait()
end
and i rather use while wait() do instead of “while true do” :slightly_smiling_face:

2 Likes

There’s really no reason to add a wait there…

2 Likes