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

How to make an if statement wait half a second until its true?

so i was creating this magnitude combat, but i really hate how it fires and avoids the if statement even if your just a few studs away from the opponent, so to avoid this problem i'd like to know how to make it wait half a second or less until the magnitude actually corresponds with the opponent and executes the if statement.

code-

if (v.HumanoidRootPart.Position - Character.HumanoidRootPart.Position).Magnitude < 5 then

--stuff here

end

2 answers

Just repeat the if statement for point-five seconds, ill do this with a for loop.

A for loop (pretty much) repeats its code for whatever number value you give it, there is more but you wont have to worry about that yet.

Basically we get our duration in seconds and how many times you want to check the if statement in that duration. We run a for loop for however many iterations we want, check the if statment and if it fails, wait for the duration divided by iterations.

local duration = 0.5
local iterations = 10


for i=1,iterations do
	if (v.HumanoidRootPart.Position - Character.HumanoidRootPart.Position).Magnitude < 5 then
		-- your code
		
		break
	end
	wait(duration/iterations)
end

I believe what you're looking for is a logical repeat or while loop. Using a for loop assumes that you know many times you want to wait for the statement to evaluate to true. Using a repeat or while loop repeats the yield infinitely; you don't know how many times you'll need to loop until the condition evaluates to true.

Repeat loop syntax works like this:

repeat
	-- code
until condition
-- where condition must evaluate to true for the loop to stop

Evidently, you can use break, but it's not necessarily a great idea.

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