# Spawning enemies best practise?

What is a nice solution to hide or despawn enemies when player is not in range?

So i am using a pool system to spawn and despawn enemies but i would like to despawn them when the player is far off. The LOD just hides the mesh but all the other components are active. So how does people tackling this generaly? Is having a giant enormous ontriggerenter collider on the player a good solution or calculating some distance from the player between every enemy or is there some other black magic thing that vould do the thing?

you can check the distance between enemy and player by Vector3.Distance().

Usually something like “if distance is bigger than x → do nothing” in the update loop.

@qkson Don’t use Vector3.Distance, do it like so

``````(firstVector - secondVector).magnitude;
``````

it saves a function call, and when you don’t actually need the distance use the square magnitude, it saves the root function kagijjer.

you can do it like so:

``````transform player;

void Update(){

if( (tansform.position - player.position).sqrMagnitude > 100){
return;
}
}
``````

this will check if the distance is bigger than 10 meters (or unity-units if you wanna get technical) and if so exit out of the update.
it says 100 in the check because we are comparing against a sqrMagnitude, so 10 X 10 = 100, you just square the range you want.
I tend to hardcode the already squared distance with thing like that, but feel free to have a variable or two for it.

edit: also, using a 3D distance is exactly like using a sphere trigger, only much more efficient imo(imo because I haven’t done any tests)

Thanks for the input . Ok so do you mean that this script is to be attached to every enemy then? Becouse they are suppose to be despawned at start. This is the part that i dont understand how to tackle. The spawning despawning of enemy and at the same time keep track of the distance between the player and the enemy.

You will need two different kinds of scripts: a single spawn scrip that is only attached to the spawner, and a despawn script that is attached to each enemy as follows:

Each of the enemies has a script attached that keeps track of the player. In Update() of that script, check if the distance to the player is greater than x (or use sqrMagnitude an check against x*x which is slightly faster, especially if xx is a constant) and despawn the enemy if greater.

Your spawner script should pick the Location to spawn the next enemy, and skip spawning if that Location is is further away than your Trigger distance (i.e. only spawn if magnitude(player.transform.Position - spawnposition) < triggerDistance).

Ahh yes thats a good way! Despawn script om enemy and a general spawn script that keeps track of player and enemy spawn points. Thanks man