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

How would I prevent 'Infinite Yields' on kill parts?

I was making an obby, and I had this script inside of a part:

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:WaitForChild('Humanoid') then
		hit.Parent:WaitForChild('Humanoid'):TakeDamage(101)
	end
end)

However, upon placing multiple parts like these, it prints this in the output: *Infinite Yield possible on line 3*

Well, something like that.

I have no clue what on earth this 'Yield' is, so can anyone help me, please?

4 comments

0

Infinite yield is a warning saying that WaitForChild() can wait forever for the child to exist because the child doesn't exist. WaitForChild() has a second parameter that tells it how many seconds to wait, so use that.

0

I did, but it still prints that.

0

That means the child doesn't exist. Using a second WaitForChild() would be irrelevant anyway because it would have found the humanoid by line 2, which means you can just index it.

0

WaitForChild will always return a truthy value unless you use its second parameter so there's no point in checking if it's truthy.

1 answer

✓ Accepted answer

Use :FindFirstChild("Humanoid"). This does not yield and returns nil if it doesn't find any Instances with that name. The new code would be

script.Parent.Touched:Connect(function(hit)
    if hit.Parent:FindFirstChild('Humanoid') then -- Found humanoid
        hit.Parent:FindFirstChild('Humanoid'):TakeDamage(101)
    end
end)

Also, yielding is making the script wait until the function has gotten something or reaching a timeout. If you want to use timeouts for :WaitForChild() you could add a second paramter which is in seconds. :WaitForChild("Humanoid", 5) will wait 5 seconds for the Humanoid and if it doesnt find it returns nil.

(if this seemed to work an upvote would be appreciated)

4 comments

0

^^^^^^^^^^^^^^^^^^^^

0

at line 3 you can just write :WaitForChild() instead of :FindFirstChild()

0

It worked! Thanks so much!\

0

@TheRealPotatoChips we really doesn't matter at this point

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