One script for all NPCs or one script for each NPC?

Hi all,

I’m developing a medieval-style fighting game that allocates some NPCs to both sides (think Mount & Blade). I’ve run into some performance issues that I’ve been trying to resolve (i.e., lots of lag with more than a few dozen NPCs fielded at once). One thing I’ve considered doing is condensing all of the scripts for the NPCs, of which there is one for each, into one master script, and from what I have read on here it seems that to do so would improve performance. My issue, though, is that I want these NPCs to behave somewhat dynamically. For example, if their target is about to attack them, instead of, say, following through with their own attack, they move to block instead. This is less critical with NPC vs. NPC combat but very important for NPC vs. player combat, as I want NPCs to be at least a bit of a threat to players, and if they don’t respond to player actions at all, they might as well not even be there in the first place.

For this reason, I feel like it would be quite difficult to govern all of that behavior from inside one single script. I don’t have much scripting experience as of yet, but my crude plan would be to constantly loop through each NPC in the game, check what their situation is, and give them some kind of an instruction based on that, but I am a) not sure that this would work properly and b) not entirely convinced that this would vastly improve performance.

I was just hoping for some general tips on the matter, since, as I have said, I don’t have much experience with scripting yet.

4 Likes

I would suggest looking into CollectionService. You would be able to add or remove NPCs into a collection based on them spawning/dying in-game. With this you would be able to have a “master script” that runs for each NPC in the collection. I believe this runs on a Tag, I haven’t used CollectionService much and may be confusing this with something else. Nonetheless, if this is the correct service, I would consider looking into it.

8 Likes

Single Script.
Object Oriented Programming or CollectionService

As you’re not as skilled with scripting, I’ll explain how to do it with CollectionService.
If you tag an NPC in CollectionService, lets say NPC. You could bind an event for each item added

You can get all objects currently with the tag with CollectionService:GetTagged(“NPC”), this returns a list of everything currently tagged, why not parse that into a function which binds events.

[color=red]WARNING![/color] Make sure to store these events so they can be disconnected if you were to remove the tag, otherwise you’ll end up with memory leaking

4 Likes

Well, we have small rule named as “Dont repeat yourself”. Its means dont use many scripts for each object. Just make a system (one script) for all.

1 Like