How can I stop the function when the model is destroyed?

  1. What do you want to achieve? Keep it simple and clear!
    I am trying to use variable “SN” to organize where models are on a path by detecting which path dots (which they tween to) they have reached.

  2. What is the issue? Include screenshots / videos if possible!
    When attempting to do math on “SN”, it will work UNLESS the model happens to get destroyed while it is occurring.

What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I’ve tried using coroutines, if not model then return nil, model.Destroying events, etc. but nothing has fully prevented errors.

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

function epaths:UpdatePos(dot: number, mdl: Model)
	local dT -- dots table
	
	if not epaths[3][dot] then
		dT = table.insert(epaths[3], {})
	end
	
	dT = epaths[3][dot]
	
	if not table.find(dT, mdl) then
		table.insert(dT, mdl)
	end
	
	if not dT then return nil end
	
	mdl.SN.Value = table.find(dT, mdl) -- problem area (SN is nil when model is destroyed)
	if epaths[3][dot+1] then
		for i = dot + 1, #epaths[3] do
			local aT = epaths[3][i]
			mdl.SN.Value += #aT -- adds the amount of enemies in front (if any)
		end
	end
end

Any help would absolutely be appreciated!

1 Like

Have you tried this?

if not mdl.Parent then
	return
end

Trying to find the model itself is unreliable, as when it is destroyed it still exists, but just has no parent and is removed from memory.

3 Likes

This fixed it! Thank you so so so much for this.

1 Like

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