- Home /
Spawn enemies in dark
Is there any way to detect light in Unity? I want to set up a system whereby enemies will continually spawn in dark areas. The player can place lighting objects (torches, make campfires etc) so ideally I'd like to write code that detects the actual light and only spawns at a certain distance away. Alternatively I could set it up so that it detects the objects rather than the light itself.
I would like it so the monsters can spawn anywhere where it's dark and not limit myself to having to set up gizmos at specific spawn points.
How would people recommend I go about this?
You could add all your lights to a master list, and then each time you want to spawn an enemy, find a random point outside the radius of a random light and try to spawn there. You'd make sure that point isn't inside any other light's radius; if it is, choose a new random light+point and try again.
Answer by IJM · Oct 07, 2010 at 02:11 PM
The easiest way would be to use point lights, create a List object of all lights that you want to detect and do something like this:
public class Player: MonoBehaviour
{
List<GameObject> Lights;
...
public bool InTheShadows()
{
foreach(GameObject L in Lights)
{
if((transform.position - L.transform.position).magnitude < L.light.range)
return false;
}
return true;
}
...
The three answers I got for this question were all valid and to a degree I've used them all in finding a solution.
I ended up using a solution that picked a random point within a large radius of the player, then checked if that point had a light nearby using the above code.
Answer by Adam Rademacher · Oct 07, 2010 at 02:11 PM
Are your lights static, or do they move around? If they're static, you can set up a bunch of predefined "spawn points" around your level that are inherently in darkness. If you have a lot of lights that move around, I'd probably suggest setting up some kind of grid-based system with nodes. When a node is within a light's range, disable it from being an active spawn point. When you want to spawn only check the active nodes.
If the player has their own light source, do a distance check based on the light from the player...
Hey Adam. I think you're on to something with the node based grid system, as that will likely be useful for some other things I'd like to implement later.
Thing is I've only ever set up worlds where the player simple moves around. How would you go about setting up a world with a grid system, especially if you wanted it to stretch over a large area?