Time for action – setting up two additional cameras in the scene

We'll have three cameras, but only one will be active at a time. Their names are:

  • Main Camera
  • LookAt Camera
  • Following Camera

Do the following steps with Scene0 loaded to add two cameras:

  1. Add a Camera GameObject and name it LookAt Camera.
  2. Set its Transform Position to 50, 7, 50.
  3. Uncheck its Active checkbox.
    Time for action – setting up two additional cameras in the scene
  4. Add a Camera GameObject and name it Following Camera.
  5. Uncheck its Active checkbox.
  6. Drag both of these cameras onto GameManager to make them children.

Look in the Scripting Reference for GameObject.SetActive. It's a method to set whether a GameObject is active or not. However, Unity can't find an inactive GameObject using the GameObject.Find() method. So we'll store a reference to each camera in a List.

Line 10 in the following screenshot of the GameData script creates the List to store the three cameras:

Time for action – setting up two additional cameras in the scene

Now we'll add all the cameras in Scene0 to the List:

  1. Select GameManager in the Hierarchy panel.
  2. In the Inspector. select Game Data (Script).
  3. Set the Size of Cameras List to 3.
  4. Now drag the three cameras from Hierarchy to Cameras Elements:
    Time for action – setting up two additional cameras in the scene

Note

It doesn't matter which camera is stored in any of the Elements.

Now that we have references to all cameras, whether they are active or not, we have the ability to make a camera active in code.

  1. Open PlayStateScene1_1 in MonoDevelop.
  2. Add code lines 21 through 27 as shown in the following screenshot:
    Time for action – setting up two additional cameras in the scene

What just happened?

Let us analyze the code that we just saw:

Line 21: foreach(GameObject camera in manager.gameDataRef.cameras)

  • This foreach loop retrieves each camera in the List named cameras
  • As each camera is retrieved, it's assigned to the variable camera

Line 23: if(camera.name != "LookAt Camera")

  • As the foreach loop iterates through the List, if the camera retrieved is not named LookAt Camera, then line 24 is executed
  • If it is named LookAt Camera, then line 26 is executed

Line 24: camera.SetActive(false);

  • This makes every camera in the List inactive if it isn't LookAt Camera

Line 26: camera.SetActive(true);

  • This makes LookAt Camera active

Switching to PlayStateScene1_2 makes the Following Camera active:

What just happened?

As this foreach loop iterates though the List, LookAt Camera will be set as inactive, and Following Camera will be set to active.

Attaching scripts to the new cameras

The LookAt Camera and the Following Camera each have a script attached.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.22.179