While loop pauses after calling an external function

The attached script seems simple; it is, though I’m having a problem where the while loop waits until the fade function finishes to restart, even though I pcalled it. I’ve tried a lot of different things to fix this but just can’t seem to figure it out. I’m willing to bet that its probably a really simple solution, but I’m having trouble spotting the issue. Any help would be appreciated.

    local fade=function(model)
    	pcall(function()
    		wait(0.5)
    		for i=1,20 do
    			model.surface.Transparency=(i/20)
    			wait(0.02)
    		end
    		model:Destroy()
    	end)
    end



    while wait(0.25) do
    	local c=(script.Parent:Clone())
    	c.Script:Destroy()
    	c.surface.Transparency=0
    	c.Parent=workspace.tmpitems
    	c.surface.Anchored=true
    	fade(c)
    end

This is likely because the fade function is hitting an error and it’s pcalled so you can’t see what the error is.

Ah, thanks, I’ll check this now.

Not seeing an error after getting rid of the pcall. Working just like before.

You should use the debugger to step through your code to see where it gets stuck.

Originally paused at the pcall, removed that, now I have this
https://gyazo.com/a91b548a7156fbf3a1eddb82ecd5cd05
https://gyazo.com/08a9f974186dbf8b33ead471fc72e6e9
Unsure why its pausing when I define the function.

A pcall just catches errors allowing the script to continue running if it encounters one. To let the while loop continue while the function is going you need to use a coroutine.

1 Like

You’re assigning a function to a variable rather than defining a function which is why it’s pausing there without the function being called yet (also because you have a breakpoint there).

1 Like

Alright thank you very much. I’ll try this.

When you call a function, it steps through the whole thing before continuing on in the area it was called. To make it so that the code just starts the function and moves on rather than yield for it, you need to use coroutines.

local fade=coroutine.create(function(model)
		wait(0.5)
		for i=1,20 do
			model.surface.Transparency=(i/20)
			wait(0.02)
		end
		model:Destroy()
end)



while wait(0.25) do
	local c=(script.Parent:Clone())
	c.Script:Destroy()
	c.surface.Transparency=0
	c.Parent=workspace.tmpitems
	c.surface.Anchored=true
	coroutine.resume(fade,c)
end

Yeah I’ve used coroutines and now it’s working as intended. Thanks for all your help.