Search code examples
unity-game-engine2dlight

How to know if an object is "lit" in Unity 2D


I want to know if an object is currently "lit", so I want to detect if the light source hits it.

I thought of a trigger as big as the light but I think that it would be quite annoying to put a specific collider for every light (I would need to modify the collider to adapt it to other light "shapes"). Is there a way / a better way than mine?


Solution

  • Yes, your way is probably the best way depending on how accurately you want to detect if an object is lit.

    • If the light cannot be blocked by other objects and the check does not have to be very precise, you can just use the Vector2.Distance method to see whether the object's center is within Light.range of the light's center.
    • If the light can be blocked by other objects, but the check still does not have to be very precise, you can cast a Raycast from the object's center to the light's center and check against Light.range again.
    • If the check does have to be precise, the best way is indeed probably just using a collider on your light. If you have many colliders in your scene, I would recommend creating two new layers: one to which you then assign all the 'touchable' lights, and another for the objects that can be 'spotted' by those lights. You can then go to Edit > ProjectSettings > Physics and in the Layer Collision Matrix, for the light layer, only tick the interaction with your 'spottable objects' layer. That way Unity won't do unnecessary collision checks with other objects.
    • If you need to be precise to the pixel, there might be a solution with shaders for that, but that would (at the very least) not be so easy to implement and could be very inefficient if used for many objects and lights.

    If you have many different, or even randomly generated, light shapes, you could create a script that, in the Awake method, sets the collider's size/shape automatically.