Why does this code only work once?

For some reason this script runs what’s in the if statement once, but not again even if there are no children inside of it.

RS = game:GetService("ReplicatedStorage")
part = script.Parent

while wait(0.001) do
	if not part:FindFirstChild(part:GetAttribute("ForageableItem")) then
		local cloner = RS.Forageables:FindFirstChild(part:GetAttribute("ForageableItem")):Clone()
		cloner.Parent = part
		cloner:SetPrimaryPartCFrame(part.CFrame)
	end
end
1 Like

Is the cloner’s name the same as part:GetAttribute("ForageableItem")? Or are you getting any errors in the output window?

Try using the debugger to step through your code one line at a time and use the watch window to see the state of all variables

It is the same name, it does work once. No errors in output, I have no idea what is wrong. I did some testing and it seems for some reason it doesn’t detect the change when the forageable is removed from the part’s children.

Can you show a small video? I just want to see how it works or what’s suppose to exactly happen, or try to explain with some images please?

also, can you add a print statement when the loop happens, make sure it’s 100% running more than once

Sure, Im just testing how to handle spawning forageables in my world, it should respawn immediately but instead doesn’t respawn at all. I did do some testing with the print statements, it does not detect that the child forageable had been removed

How exactly are you removing the forgeable? with a LocalScript, if so, are you detecting it to be placed again by a LocalScript or a Script?

LocalScript fires the server of an event.

So the server removes and adds the forgeables, not the client?

Yes the client tells the server to remove them

Okay, can you try something for me? after you clone it originally, in the same if statement that checks if it doesn’t exist, can you wait a few seconds, and do cloner:Destroy() and then see if it re-appears by itself?

Can’t believe a wait() caused me this much pain. Thanks man.

Well, that cloner:Destroy() function makes it delete itself without you pressing e on it, but did waiting longer fix your entire issue without the Destroy() function?

Yeah it was just the wait that solved it

1 Like

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