I’m trying to make a wave defense game where enemies spawn each round. How do I control all the enemies to attack the player? I tried putting an AI script to each enemy but it lags the game after 10 NPCs spawn.
I’m not sure if this is the response you were looking for, but here’s a youtube video of a very talented programmer who is phenomenal at explaining how to do things.
He explains what he does step by step. Although the video is long, it achieves your goal.
In his video, he creates humanoids to pathfind. You would have to edit the code to meet your requirements, but given that you already have the AI script it would just be copy pasting
Putting it in a single script won’t solve the problem then. It’s fundamentally the same thing to the computer. Each NPC basically gets scheduled to run some code and runs the code. You’ll have to figure out how to make your current code more performant to make a single script version work.
You need to look at things that take a time to run amd call those functions less or more efficiently (some people check all of workspace for example for all players when you should put them in a folder or tag them or something so you don’t have to run everything through). Secondly if you are using a loop, increase the wait time in those loops which will give you more time for others to run.
Third, depending on your specific game you might be able to optimize the character and how they move specifically, but this unless you can make massive adjustments will likely not be your biggest speedup and the 2 above are worth looking into more.
I should note that there is one case where it could be different. And that’s where you calculate info once and share it between them. You can do that across multiple scripts with a module though if you wanted.