Hello,
I’m currently making a scrolling topdown shooter (think Gunksmoke, Ikari warriors, Commando etc.) and got most of my code working, so now it’s time to start worrying about putting together a prototype level to see how well it all plays together, and that’s where I’ve run into a problem I would like some advice on.
Background: My programming skills are at an happy amateur level, but I manage to solve most problems I’ve encounter. But when it comes to taking the performance of the code into account I’m a complete beginner, hence this post.
The issue is how to handle the spawning/activation of all the enemy’s, which there will be several hundreds of, in an efficient way. At first I thought that I’d just have each enemy check the distance to camera then activate all it’s components (AI, Pathfinding etc.) but that would be like (lets assume I have 300 enemies per level) 300 function calls per frame. Ok I don’t have to check every frame so I could probably do a timebased solution and check ~4 times per second instead, which would give 1200 calls per second. From my point of view this seems like a lot of unnecessary calls and not to efficient.
So just to muck about I wrote a EnemySpawnManager script that does
enemyList = GameObject.FindGameObjectsWithTag("Enemy"); on level load, then loops through it like
foreach (GameObject enemy in enemyList){
if (enemy != null) {
objectPosition = mainCamera.camera.WorldToViewportPoint(enemy.transform.position);
if (objectPosition.y < 1 objectPosition.y > 0)
enemy.gameObject.active = true;
if (objectPosition.y > 1 || objectPosition.y < 0)
enemy.gameObject.active = false;
}
}
So now instead of having 1200 function calls per second, I just loop through an array with size 300 every 250ms and enable/disable all enemies depending if they are on screen or not.
But as I really have no idea about how to write efficient code I can only assume that the second solution is better.
This is one of them problems that probably have been solved 1000’s of times, but I’ll be damn if I could find any code examples or unity specific code on how other people solved it (also in a weird state of mind since it’s 6:30 in the morning and I’m running out of energy drinks).
So to anyone that have experience in this, how would you do it? Do I even need to worry about this? I’m familiar with the expression “premature optimization is the devil!!” but as this code will be running a lot in the background I want to be sure that I get it right or get some advice on best practices.
Would appreciate any pointers/advice
Regards,
Arne, one of the most happy elf’s you’ve ever seen!