Sitemap

How to Make a Interactive Camera using Cinemachine and C#

3 min readFeb 3, 2023

Objective: Control your Virtual Cameras with C#!

Controlling virtual cameras with C# is similar to how you would control any other object with C#. We start with accessing the proper library. In this case we need to use the Cinemachine Library.

You will also need the Cinemachine virtual camera component.

Press enter or click to view image in full size

On the Unity side of things, we need to create an empty object. I called mine “Camera Controller”, once done add the script to the object. Since we serialized the Cinemachine Virtual Camera component in the inspector we will see a place to add our virtual camera.

Press enter or click to view image in full size

Don’t forget to attach your virtual camera in the inspector.

Press enter or click to view image in full size

Now we have a handle on the virtual camera. We can now access all of their settings. Let’s start simple with something like switching the LookAt object.

To start this off we need 3 Game object variables. In this tutorial We have a sphere, a cube, and we need a variable for the “target” that the camera will be looking at.

Press enter or click to view image in full size

These are serialized so we can easily assign the cube and sphere in the inspector.

Press enter or click to view image in full size

In the start method we assign the target to one of the objects, let’s set it to cube. With the target set to one of the objects we can set the LookAt object to the target’s transform.

Press enter or click to view image in full size

Now we need to create a method to change the object the target is assigned to using two if statements.

For this tutorial we are going to have the virtual camera’s LookAt object with the push of a button. In the update method we are going to check for the “R” key press. If the player presses the “R” key, we will call the Change Target method and reassign the LookAt object.

Press enter or click to view image in full size
Press enter or click to view image in full size

Now you know how to access your and control your virtual cameras using C#. Don’t be afraid to experiment with your virtual cameras, and I’ll see you in the next tutorial!

--

--

No responses yet