In this lesson, you will learn how to programmatically manipulate the properties of a Cinemachine Virtual Camera at runtime to create reactive, gameplay-driven cinematics.
Beyond the Inspector
While we often configure cameras in the Inspector, scripting allows us to adjust camera behavior based on in-game events, such as zooming in when a player enters a "Sniper Mode" or widening the field of view when they gain a speed boost. To control a virtual camera via script, we interact with the CinemachineVirtualCamera component and its internal "Components," such as the Lens or the Body.
Accessing the Lens
The most common property to adjust at runtime is the Lens settings. For example, if you want to dynamically adjust the Field of View (FOV) based on the player's movement speed, you can access the m_Lens field directly.
First, ensure you have the correct namespace at the top of your script:
using Cinemachine;
Then, you can modify the lens in your Update or FixedUpdate loop:
public CinemachineVirtualCamera vcam;
void Update()
{
// Dynamically increase FOV based on player velocity
float speed = playerRb.velocity.magnitude;
vcam.m_Lens.FieldOfView = Mathf.Lerp(60f, 90f, speed / 20f);
}
Adjusting Camera Components
Virtual Cameras use modules like CinemachineComposer or CinemachineTransposer to determine how they track targets. You can access these components using GetCinemachineComponent<T>(). This is useful if you want to change the "Dead Zone" or "Soft Zone" sizes when a player enters a combat state, effectively making the camera more or less responsive to movement.
void SetCombatMode(bool isCombat)
{
var composer = vcam.GetCinemachineComponent<CinemachineComposer>();
if (composer != null)
{
// Tighten the dead zone for combat
composer.m_DeadZoneWidth = isCombat ? 0.1f : 0.5f;
}
}
By casting these components, you gain fine-grained control over the camera's framing logic, allowing your virtual camera to "feel" different depending on the gameplay context.
Key Takeaway: By accessing the m_Lens field and using GetCinemachineComponent<T>(), you can procedurally modify camera behavior to match the intensity and requirements of your gameplay in real time.