Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is my script timing out when locating Players?

Just been working on a script that allows an NPC creature follow the closest player when close enough and when the player isn't close it just minds its own business walking around. Everytime I run the script I'm recieving Script Timeouts and I honestly dont know why.

Action.Text = "Idle"

local function Movement()
	print("Moving")
	Action.Text = "Walking"
	Walk:Play()
	local TI = TweenInfo.new(
		math.random(2,4),
		Enum.EasingStyle.Linear,
		Enum.EasingDirection.InOut,
		0,
		false,
		0
	)
	
	local PP = {
		Position = HRP.Position+Vector3.new(math.random(-6,6),0,0)
	}
	
	local T = TS:Create(HRP,TI,PP)
	T:Play()
end

while Action.Text == "Idle" do
	print("Currently Idle")
	Idle:Play()
	wait(math.random(2,6))
	Movement()
end

while true do
	for i,v in pairs(game.Players:GetChildren())do
		local Character = game.Workspace:WaitForChild(v.Name)
		if (Character.HumanoidRootPart.Position - HRP.Position).Magnitude <= 30 and (Character.Position - HRP.Position).Magnitude >= 3 then
			print("Found Player and chasing") 
			Run:Play()
			if Action.Text == "Idle" or Action.Text == "Walking" then
				Action.Text = "Running"
				Humanoid.WalkSpeed = 25
	        end
	 end
end
end

while true do
	for i,v in pairs(game.Players:GetChildren())do
		local Character = game.Workspace:WaitForChild(v.Name)
		if (Character.HumanoidRootPart.Position - HRP.Position).Magnitude >= 30 then
			print("Player too Far")
			if Action.Text == "Run" or Action.Text == "Walking" then
				Action.Text = "Idle"
	        end
	 end
end
end

4 comments

0

you forgot to add a wait() to the loop

0

Yeah, he did lmao

0

I don't see any waits on lines 31 - 43, nor 45 - 55

0

oh alr

1 answer

✓ Accepted answer

First of all use GetPlayers() instead of GetChildren() next use GetService for services and your first infinite loop will loop infinitely (thus the name) so it will never reach the second loop, either use coroutines or spawn so that it will reach that loop and use yield (so wait()) in your infinite loops or else you will get those timeouts and other errors

see this article about loops

This discussion is preserved as it was. New answers, comments, and votes are closed.