Detecting when an object exists in loop

  1. What do you want to achieve?
    I have a boss npc, and it creates a folder object named “battleStarted” and parents it to the npc when a player is within range and destroys it after killing the player/no more players in range
  2. What is the issue?
    The battleStarted folder just exists as a tag, and i want to have a function executed from another script only while the battleStarted object exists, however when i have tried solutions it either runs the loop when the object doesn’t exist, or doesn’t run it when the object does exist.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I’ve seen a few topics but none of them really worked for what i was doing, so i’m making this post.
-- creator script code
local bTag = Instance.new("Folder")
bTag.Name = "battleStarted"
bTag.Parent = script.Parent
-- loop script code
local btag = nil

bTag = char:WaitForChild("battleStarted")

while bTag ~= nil do
	ExpandShockwave()
end
1 Like

try creating a BindableEvent to start/stop the loop when conditions are met and parent it to the script containing the loop

I feel like this is what you’re trying to go for:

You can clone the object into a folder and when the object is present in the folder you can do:

folder:ChildAdded:Connect(function(child)
	if child == "name of child" then
		-- code here
	end
end)

Tried this as nothing_1649’s solution wasn’t working, and i have it to print “detected”, but when i test the game, it repeatedly spam prints “detected” without the object being created, and when it is created, it stops, and then continues again when the object is removed

-- loop script code
char.ChildAdded:Connect(function(child)
	if child.Name == "battleStarted" then
		print('detected')
	end
end)

image

That is some very unusual behaviour.
Could we try printing out the child and see what is being added?

image
image

It’s printing the name of the object, even though it doesn’t exist.

Instead, try this:

while bTag:IsDescendantOf(workspace) do
	ExpandShockwave()
end

I just thought of a different way to do this anyways, but thanks for your guys’ help!

Even though you said you found a solution, one issue with this code is using WaitForChild. WaitForChild will yield the current thread until a maximum time is reached. You should used FindFirstChild instead.

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