Repeat loop not working

Hello! I’m working on a Splinter Cell type game and I have this light part that will look for the player and if the raycast hits will bring up their “hidden” level. However I’m having trouble with the loop that checks if the player is in the light, it’s just not repeating!

repeat
	wait(.2)
	for i,v in pairs(game.Players:GetChildren()) do
		local char = v.CharacterAdded:Wait() or v.Character
		local rayorig = script.Parent.Position
		local raydes = char:WaitForChild("Head").Position
		local rayresult = workspace:Raycast(rayorig,raydes)
		print(rayresult.Instance.Name)
		if rayresult.Instance.Name == "Head" then
			print("yep")
		end
	end
until false

This is my whole script right here, and this is what happens.
project: echelon - Roblox Studio - Gyazo
Clearly it’s not looping but why is that? Any help?


Here’s a miscellaneous screenshot if needed.

P.S. While true do isn’t working either.

1 Like

this one breaks it all, you have to just use v.Character, no need to wait for one

Also, you are using raycast wrong, it has 2 main arguments Origin and Direction
you are missusing the Direction argument just as destination, which is wrong

2 Likes

I’ve tried that but this pops up.
image
This makes me believe the character hasn’t loaded in yet.

Add nil checks to make sure character is fully loaded

if v.Character then
-- stuff there
end
2 Likes

The script is not looping because of this line v.CharacterAdded:Wait() or v.Character. It will wait until the CharacterAdded event is fired, which only happens whenever the character (re)spawns. So, when looping through the players, if the character is already alive, it will yield infinitely. At least that is my theory.

BTW

You can use :GetPlayers() instead of GetChildren.

You could also make use of a while loop:

while true do
    wait(.2)
end
-- is the same as
while wait(.2) do
end

Like znimator pointed out, you can check if the character exists wtih a if statement.

3 Likes

This worked, thank you!
(character limit text)

1 Like

Btw I think your raydes variable is also wrong. A vector from A to B is equals to B minus A.

local raydes = char:WaitForChild("Head").Position - rayorig

You can specify a max range like so:

local raydes = (char:WaitForChild("Head").Position - rayorig).Unit * rangeHere
2 Likes

I was thinking the same thing but then he posted the solution so I left it alone.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.