Creating Security Cameras In Unity
For my stealth game, you must navigate past 2 security cameras without being seen. Here’s how I made them.
Today’s Objective: Create the security camera functionality to detect the player and start the Game Over cutscene.
I currently have 2 cameras set up on the pillars. “Camera Left/Right” object holds the whole camera, and has zero rotation. “Camera Rotator” is what I have animated to turn, and contains the tilted rotation values in its transform. “Camera Cone” is the visual representation of the camera’s field of view, and has a renderer and a mesh collider on it.
I want to use the collider’s OnTriggerEnter method to detect the player inside the camera’s field of view. Since the collider is on the “Camera Cone” object, that’s where my “Security Camera” component will go. Although I’m personally not a fan of having management components not on the base object.
After creating the “SecurityCamera” class, I know I will need to do a few things when the player is detected. These will include: changing the “Camera Cone” material and enabling the cutscene object.
While I could hard-code these in using variables, I would rather make the code able to execute any actions I want without modifying code. For that reason, I will use the UnityEvent variable type:
OnTriggerEnter and OnTriggerExit are builtin Unity methods that can be used on an object with a collider. They are very useful, but remember, the collider needs to have its “Is Trigger” boolean ticked. Otherwise you need to use OnCollisionEnter/Exit.
I could skip the below coroutine and simply enable the cutscene object from the UnityEvent list. However, I wanted a short delay there, to let the player see the red light, so I made the coroutine simply for that reason.