Using CollectionService to run a folder with code for every enemy

Hello, everyone.

Recently, I’ve been hard at work on a new project of mine, and I’m having a good time making it. However, after spending one or two days writing the AI for the basic enemies, I soon realized that copying and pasting a clone of the AI folder into every enemy was not a good way to go about things, as having multiple scripts running at once would cause massive lag (it did, indeed, cause massive lag).

Then I came across CollectionService, which apparently can be used to make one script run for every single thing in the game that has a specific tag attached to them. This apparently worked with enemy AI, and I quickly jumped on it trying to use this for my game. The issue is, it’s not compatible with the system I’m using, at least as far as I know. And that’s what I want to figure out.

Basically, I set up what is essentially an attempt at a behavior tree, with a ‘Main’ script dictating when every other script should turn itself on and off in order to make the enemy do different things, something like this:

image
>MAIN - Dictates when Pathfinding and Chase should be enabled or disabled. Attack is handled by Chase, hence why it’s a child of Chase. It also handles target selection.
>PATHFINDING - Pathfinds the enemy a way to its goal, when there is nothing to chase.
>CHASE - If there’s something to change, it locks the enemy onto the Target’s value and chases it down. If the enemy gets close enough to its target, it will attack.
>ATTACK - Makes the enemy attack its target.

It worked really well, and I’ve used it a lot for coding AIs ever since I first attempted it. I could not for the love of my darn life do it properly using just a single script, and so far, using this method has had no disadvantages (at least, until I realized the whole lag thing).

I’ve tried using a single script again and port/adapt the code into it and use it with CollectionService, but it’s wasting what little free time I have left and giving me an average headaches per day far greater than what the healthy human should have, so I can’t go down that route.

So, TL;DR: Is there any way I could possibly use CollectionService to run this one folder at the same time for every enemy?

Let me know if you have any ideas, please. I’d love to come up with a solution that isn’t going to kill what little brain cells I’ve got left… Feel free to ask any questions about any of this!