Function Trying to Run on Destroyed Model?

So I have lots of pet NPCs in the game of different kinds, so I tagged them with CollectionService and have scripts that animate them according to their tag. So all the NPCs tagged “Cat” get one animation script, “Dog” gets another, etc.

But I am having a weird problem. The script seems to try to continue running AFTER the tagged model has been destroyed. After a tagged NPC gets destroyed, the code then keeps returning this error:

ServerScriptService.Pet Scripts.Cat Script:73: attempt to index nil with ‘position’

The line of code simply references the PrimaryPart of the NPC. I don’t think the whole code is relevant so I won’t bother pasting it here. I am applying the code to the NPCs using this function:

CollectionService:GetInstanceAddedSignal(“Cat”):Connect(function(pet)

Do I need to disconnect this function for an NPC when that NPC is destroyed? I thought destroying a model disabled all of the events connected to it. No?

Things I have ruled out:

The pet is not still in the workspace after destroyed somehow.
The pets of the same kind are not being confused with each other.
I tried if pet = nil, then disconnect function … but that didn’t work either.

Thoughts?

1 Like

Hi,

certainly some more code would probably be helpful here. But first some misconceptions:

When a part or model is destroyed, any functions connected to any of it’s events are disconnected. But, notice that you are not connecting to an event in a part or model. You are connecting to an event of the CollectionService. So this won’t be disconnected, no matter which part in the workspace you destroy.

However, it seems that this function only executes once per added instance (pet). That’s why presumably you have made a loop in there or something that keeps running, and doing something with the pet.Position. When the pet is destroyed, this no longer works.

It may be heavy on your game to have a lot of pets continuously running these loops, but to solve the immediate problem, you probably want to at least end the loop when the pet can no longer be found.

2 Likes

Excellent, thank you! Avoided loops, player movements prompt the pets to move. Slowly … very slowly, I am learning how to do this.

2 Likes