Unity : Cinemachine and Timeline (Part IV)
In this article we continue our path with Cinemachine, and today we try to create more Virtual Camera to Look At the Cube from different position and to see what happen.
To set up the Scene, for now, I delete my Virtual Camera and I create another one from scratch, then I duplicate it to obtain another four, so we have five Virtual Camera.
The position of these Cameras is absolutely “random”, feel free to set up the Scene in whatever way you want.
My Scene is now like this
I have this sort of “circle of Cameras” around the Cube.
If we want to see better where we have the Camera, we can use the icon system
After we set the Scene, the next step is
“How can we pass from Camera to Camera?”
There are two ways to do that :
enable / disable the object
Maybe is not totally clear, but what we happen is simply that every time we disable one Camera and enable another one, the other take control of the Visual.
The second way is set the Priority of the Cameras.
We have this option here
Higher the number, higher the priority.
Every time we change priority of CM vcam1 from 10 to 1, Unity search the nearest Camera with higher priority.
Let’s try in code with first method.
Ok so now we have C# script.
Easy test, we have three Cameras (I disable two of them for simplicity), and what we want is press a key, disable two Camera and let on live state only one.
The script is incredible easy :
We take the reference of three Cameras and pass them directly through Inspector, by default in Start all Cameras are active, when we press R we disable two Cameras.
Ok, now for sake of test I change the position of the Cameras so we can see better what happen when we press R button.
In Main Camera I have the script and I pass three Virtual Cameras inside it.
We set the first Camera to priority 11 or 15, and test it
A better way to set up our code is to use a List<> or Array to our Cameras
in the second for loop I use _cameras.Length - 1,
because _cameras.Length is 3, with - 1 = 2.
And ecause we check if
i < 2, it means it does only two iteration,
0 and 1.
I hope is clear, sometimes the use of Array or List can be “tedious”, but only because we need to remember that Collection in programming are zero based, so if we try to access at some index with a loop, and we check all the item it stores, we have to watch out to not find ourself out of bounds.
NullReference and OutOfBound are two of the most common errors that can happen.
Don’t worry, is absolutely normal.
We can use obviously
This can normally be a problem, because we repeat the code for every object we have within a Collection, but this is just a test and we have literally two lines of code, so we don’t worry too much about it.
In the next articles we see more useful things about Virtual Cameras.