# Unity How to manage multiple enemies/mobs in open world RPG

## Recommended Posts

Hi there gamedev community,

I'll go directly to the question.

How is the best way to handle A LOT of enemies without slowing my game process?.

I am currently testing, i have a vector of an "enemy" class, and its fine for my testing purposes. The problem is, imagine i have +3000 enemies in my map, how can i manage to execute their IA Behavior, and test who the player attacked, etc.

Im currently using a for loop from 0 to MAX_ENEMIES_IN_GAME, but with +3000 enemies my fps will drop to almost zero hahaha.

Sorry for my bad english, i'll re-write the question if needed, just ask!

Thanks

for (int j = 0; j< MOBS_EN_JUEGO; j++)
{
_mobs[j].run(_pj.getX(),_pj.getY(),&_pj); //Make the enemy walk to player position
}


EDIT: I thought something like, only test the enemies who are close to the player, but for selecting those enemies, i would have to do the same for loop, so... haha.

The only way i can think of it, its to make a bunch of 100x100 areas instead of a full map, so i can forget about the enemies that are not in the area

Edited by Azokasion

##### Share on other sites

for() loops aren't slow. The logic they contain can be slow. Iterating over 100,000 objects shouldn't be a problem. If 3000 is slowing you down, it's the code within the for() loop. Could you post your run() function?

• Are you re-doing the pathfinding every tick? You should only be doing the pathfinding when the environment changes, and just cache the result.

• Are you doing complicated AI decision-making for every entity every tick? Try doing it every N tick. i.e. if you have 3000 entities, do 0-1000 AI logic one tick, 1000-2000 the next tick, and 2000-3000 the third tick. You still have every entity update/move every frame, but they only "rethink" every few frames.

• As you mentioned, the farther away an entity is, the less frequently it should think. If an entity is 500 feet away, offscreen, maybe make it only think once every ten ticks. If it's really far away, don't update it at all if your game design permits it.

• My guess is your real slowdown is that you're accidentally drawing all the entities even when they are off-screen. I doubt the code you posted is the real slowdown (unless it's actually doing pathfinding in the run() function). Have you actually profiled yet? Profiling tells you where your program is spending the most time.

Actually, i dont implemented all that enemies yet, i was only trying to get a picture of some programming tricks for the case, so i dont really know if my game will slow down that much.
You gave me some nice ways to do it in case my design needs it, thank you, i would never came with the second one haha.

As for the drawing, i coded a camera system that ensures im only drawing only what i can see.

##### Share on other sites
SeanMiddleditch    17565
Run a profiler on your game. Find out _for sure_ where the slowdown is.

If you're on Windows, use Very Sleepy as a free profiler. There's also a profiler built into Visual Studio.

If you're on Linux, consider perf, which is a very capable tool (though not the easiest to use because, you know... Linux).

##### Share on other sites
Ashaman73    13715

The problem is, imagine i have +3000 enemies in my map, how can i manage to execute their IA Behavior, and test who the player attacked, etc.

Here are some tips with pseudo code:

1. Have a next update/next ai time like this:

obj::updateAi()
{
// do something with obj

if(is_player_around==true) {
// hi-frequent update time
obj.next_ai_updattime = current_time + 100;
} else {
// low-frequent update time
obj.next_ai_updattime = current_time + 3000;
}
}

main_loop:
for each obj in my_game_objects do
{
if(obj.next_ai_updatetime<current_time) {
obj.updateAI();
}
}



2. use timed events, e.g. like this

addEvent(event)
{
obj.next_event_time = min(event.execute_at,obj.next_event_time);
}
process_all_events_up_to_time(obj,time)
{
min_event_time = MAX;
for each event in obj.event_list do
{
if(event.execute_at<current_time) {
event.execute(obj);
obj.event_list.remove(event);
} else {
min_event_time = min(min_event_time,event.execute_at);
}
}
obj.next_event_time = min_event_time;

}

main loop:
for each obj in my_game_objs do
{
if(obj.next_event_time<current_time) {

process_all_events_up_to_time(obj,current_time);
}
}


3. for objects, which needs to be updated really seldomly, e.g. a pusling shrine which is active for only a few seconds after being triggered, use the event system instead of the update system like this:

pulsing_shrine_triggered_update(obj) =
{

// do something, e.g. heal nearby creatures

// done ?
if(!done) {
// trigger again in 1 second
}
}



4. if you use the tips from above, replicate the times in an array for faster memory access,because you really need to test only the timestamps most of the time. No need to access large objects all the time. Thought the performance benefit might be small to tiny ;-)

Edited by Ashaman73

##### Share on other sites
SeanMiddleditch    17565
(again, profile first, but...)

You can also use "AI Level of Detail." Enemies that are far away from the camera don't need to update as often because the player can't see them well or at all. They also don't need to have high-fidelity AI.

Reduce the frequency of AI ticks for an enemy based on distance and direction from the view frustrum. Far-away enemies don't need to be all that smart to look believable. Enemies that aren't even near the frustrum can't be seen at all and aren't likely to be seen soon, so they can be really dumb.

Also consider just simplify expensive calculations for those enemies. If the player can't actually see an enemy, there's no point to do high-fidelity path-finding. If the enemy is far enough away they can even just teleport around with nobody being the wiser. The same goes for any other expensive calculations. Friendly inter-NPC interactions can be disabled and inter-NPC combat can be simplified to basic rolls instead of the full combat system.

And of course, if the enemies are really far away, they can just be put on ice and stop updating entirely, or update very very infrequently.

##### Share on other sites
Norman Barrows    7179

Actually, i dont implemented all that enemies yet, i was only trying to get a picture of some programming tricks for the case, so i dont really know if my game will slow down that much.

sounds like the thing to do is a rapid prototype of 3000 enemies, and un-optimized AI. IE step one should be to see if brute force is good enough, or whether you have to "get jiggy with it".

if it turns out that a vector of 3000 badguys just updating them all isn't fast enough, reach for the profiler. it may indicate a need for the optimizations as described by Servant, Sean, and Ashaman.

then you can build the game knowing your already tested system will perform well.

always test brute force first.  often it can be good enough. this is an approach i learned from Carmack and Abrams.

if brute force won't cut it, then its time for fancy algorithms.

##### Share on other sites
baseball435    286

Depending on how large your map is you can split the map into separate sections or chunks. Each chunk would contain the entities that lay within it's bounds and it would only update/render those entities if the player is in or near the chunk.

##### Share on other sites
Norman Barrows    7179

in caveman, i was having problems with lots of active targets and AI and accelerated time.  in the end, i went with a 128x limit on accelerated time with badguys nearby and full AI. at time acceleration above 128x with no badguys, i simply model the results of running the non-badguy AI (IE everything eventually wanders off and gets removed from the simulation) , but don't actually run the AI at all.

and of course if all else fails , you can always have the AI cheat. <g>.

## Create an account

Register a new account

• ### Similar Content

• By mmortall
Genre: Story Puzzle Technologies: Unity Web Player, C# Mono, Objetive-C Platforms: iOS   Language: English, Russian   Websites: App Store www.welldonegame.com Facebook group   Overview: Puzzle with love story. You need to solve mazes to reach girl you love in a beautiful environment. 80+ completely diverse stages, that show the history of Boy’s and Girl’s relationship AR mode (for iOS 11) Procedure generated nonrepetitive mazes Infinite mode with leaderboards Collecting unique postcards   Slogan: Love is a maze   Video   Screenshots   Needs your feedbacks

• My first goal is to build in python a text-based (next version will have graphics) adventure game scenario where a player enters a tavern, and goes on a quest. Earns money, buys weapons and gets in a fight.

So I've got four ideas for games I want to build.
1. a space simulation where a mute evolving clique is tasked with colonising planets - it's also a social network.
My next goal is to build a 3rd person shooter and streets of rage style framework for a action/adventure game based on my story which is about God's mightiest heroes (with mutation sandbox) versus the devil (read pinhead meets bizarro superman).
I also want to build in python, a 3d isometric rpg/sim that looks like the sims 1 but thematically is more like Bully or GTA1, but plays like Hell's Kitchen DS combined with Dofus, with environments combining elements of Phantasy Star, Sonic and art photography of convenience stores, etc.
I also want to build an epic adventure story in RPGMakerMV.
Any advice as to what else I should build in between to get closer to my goal projects.

In a few weeks I'll have my first game, I'm not really sure how to turn it into an executable file so i can share it with people who don't have python installed.

• I've been using async-await in Unity 2017 for awhile now and went through some hurdles getting it to work properly with the unity way of doing things. In order to avoid anyone else suffering the same problems I've posted a tutorial with what I've learned here:

http://www.stevevermeulen.com/index.php/2017/09/23/using-async-await-in-unity3d-2017/

•
Hi, I would like to have an opinion on what I can improve and change in my first published game.
The game was made on Unity3D.
Thank you.

• You are a US Army soldier, and one day an unknown enemy attacked your base. Now your task is to survive and protect the base. There are a lot of weapons in your arsenal. Survive this nightmare at any cost.