This codelab will teach you how to modify an existing Unity game for Android to run on a Google Cast device. You will also add the necessary UI components based on the Google Cast Games UX guidelines.

What you'll learn

What you'll need

Experience

How will you use use this tutorial?

Read it through only Read it and complete the exercises

How would you rate your experience with building Unity apps?

Novice Intermediate Proficient

How would you rate your experience with building Android apps?

Novice Intermediate Proficient

For this codelab we will be using one of the Unity tutorial games called "Survival Shooter" which shows many of the basic game making techniques. The game is a top-down survival shooter with a young boy having a nightmare that his toys come to life as members of the undead, but luckily he is armed to defend himself.

We're going to skip the Unity tutorial and jump right into making it work on a Google Cast device.

First you need the completed tutorial version of the Unity sample game:

Download codelab sample zip file

Unzip the file into a working directory on your development computer.

Let's run the sample game in the Unity editor.

Start Unity

  1. Start Unity. Click on the Open Other icon and select the directory where you unzipped the sample game. Select the begin_project folder. Click on the Open button and the sample game will open in the Unity editor.
  1. Click on the Play button to play the game on your computer. The game controls are:
  1. Click the Play button again to stop the game.

If you have not developed an Android application with Unity before, this section shows how to configure the Android build settings in Unity.

Configure the Android SDK

In Unity, click Preferences > External Tools > Android SDK Location, then select the folder where you downloaded and unzipped the Android SDK.

Configure the Android Player

Configure Unity to build an Android application:

  1. Click File > Build Settings... to open the Build Settings window.
  2. Select Android in the platform list, if it isn't selected already.
  3. Click the Switch Platform to make Android your default build target (it will take several minutes for the Unity editor to import the Android assets).

Configure the Bundle Identifier

  1. With the Build Settings window open, click on Player Settings...
  2. Expand the Other Settings section by clicking on it.
  3. Enter the Bundle Identifier. The bundle identifier should be unique and typically of this form: com.<yourcompany>.<appname>. We will use "com.example.game".
  4. Change the Minimum API Level value to Android 4.4.
  5. Append to Scripting Define Symbols: ";MOBILE_INPUT" (semi-colon separator) and press the Enter/Return key to save the value.
  6. Close the Build Settings dialog.

Save and Run

  1. Save your project using the Unity editor File menu.
  2. Connect your Android device to your computer using a USB cable.
  3. Select File > Build & Run in the Unity editor (the Build Setting dialog might be displayed again; just click on the Build & Run button). When prompted for a name for the APK file, enter game.apk (it will take Unity several minutes to build the APK file and upload it to your mobile device).
  4. Once the games starts playing on your mobile device, you can touch the screen to aim and shoot the gun. We don't have any mobile controls to move the character around yet.
  5. Swipe from the right side of the device towards the screen to display the system navigation buttons. Use the back button to display the pause dialog (the pause dialog will look small; we will fix that later).
  6. Quit the game.

The game isn't designed for a mobile experience yet. We will add a joystick controller that will allow the user to play the game on the mobile device and use the mobile device as a controller when casting the game to a TV.

Frequently Asked Questions

There are millions of mobile devices with powerful GPUs and sensors ready to send amazing interactive content to the largest screen in the home. Integrating the Remote Display APIs for Google Cast means you can harness all those increasingly powerful CPUs and GPUs in your mobile device and build dual display games where you use the mobile device to render both a local display and a virtual one. This allows you to create games that look beautiful, using the power of a phone or tablet and send that amazing world to the TV!

Because you can utilize the power of the mobile device, all the power of the platform, like payments and various API's already exist for you.

If you are making a game that can be played on the device itself, away from the television, we call this a cast-enabled game. If the game can only be played as part of the Google Cast experience, in front of a big screen, this is what we call a cast-required game. We will be developing a cast-enabled game for this codelab.

You can use the mobile device sensors to create abstract controls which interacts with action on the screen via motion or touch. Or you can create virtual controls where the player touches something on the device to control something else on the screen. For the codelab game we will create virtual joystick controls for moving the player and controlling the gun.

For visual design it is important not to fatigue the player by making them constantly look up and down. The television's experience should be designed to be viewed from across the room. This means big, readable text and nothing that looks "tappable". We will be creating UI's that are appropriate for both the mobile device and the TV.

Let's go over some of the Google Cast concepts. Here are some Google Cast terminology that we will be using in this codelab:

An app running on the sender connects to a receiver device, such as a Chromecast, and passes along an Application ID to load. The receiver device loads that application from the cloud. The sender can send media control commands or custom messages to the receiver.

Remote Display for Android and iOS allows app developers to take full advantage of the multi-screen Google Cast model. With our Remote Display technology, you trigger the experience directly from within your game or app. It follows the same simple model of all Google Cast interactions, just tap the Cast button and go!

To make it easy to support Google Cast devices in Unity games, Google has developed a plugin. We will show you how to add the plugin to the sample game in this codelab.

Frequently Asked Questions

To be able to use the Google Cast Remote Display API in your app you first have to register as a Google Cast developer using the Google Cast Developer Console. Use the Chrome desktop browser with the Cast extension installed to register as a Google Cast developer (Registering as a developer requires a nominal fee of $5 US).

Once you are registered, add an application:

  1. Click on the Add New Application button to add a new application.
  2. Select the Remote Display Receiver option and enter a name for the application, for example "Remote Display Codelab". Make a note of the Application Id that is displayed in the console for your new Remote Display receiver app.

Next, register your Google Cast device (this will allow you to test your app on your device before publishing the app):

  1. Click on the Add New Device button.
  2. With the Add Cast Receiver Device dialog open, click on the Cast icon. Select your device from the list. This will launch a special receiver on your Cast device which will display and read out aloud the device serial number.
  3. Enter the serial number and description for your Cast device.
  4. Click on the OK button to the add device. It will take 15 mins for your device to be registered.
  5. After the device is registered, restart your Google Cast device.

Frequently Asked Questions

With the Remote Display API, you trigger the Cast experience directly from within your game. It follows the same simple model of all Google Cast interactions, just tap the Cast button and go! It increases the discoverability of the feature and is a big difference compared to competing technologies.

Installing the Google Cast Remote Display plugin

The Google Cast Remote Display Plugin is available in the Unity Asset Store and on GitHub:

Download plugin package file

Follow these steps to add the plugin to the game project:

  1. Select Assets > Import Package > Custom Package in the Unity editor.
  2. Choose the downloaded GoogleCastRemoteDisplay.unitypackage file.
  3. The Importing package dialog is displayed. Click the Import button to import all the assets in the package into the game project.
  4. Verify that you see files were added under these project folders:
  1. Assets/Plugins/GoogleCastRemoteDisplay
  2. Assets/Plugins/Android/GoogleCastRemoteDisplay.aar
  3. Assets/Plugins/iOS/GoogleCastRemoteDisplay

Adding the Android Libraries

The Android portion of the plugin depends on these libraries:

Make of a copy of these Android SDK directories into the project Assets/Plugins/Android folder:

You should now have the following in the project Assets/Plugins/Android folder:

Create a new text file called AndroidManifest.xml in the Assets/Plugins/Android project folder. Use the following AndroidManifest.xml file contents and change the package to match the Bundle Identifier you configured in the Unity build settings: com.example.game

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.game" android:versionName="1.0" android:versionCode="1" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:theme="@android:style/Theme.NoTitleBar" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="false" android:isGame="true" android:banner="@drawable/app_banner">
    <activity android:label="@string/app_name" android:screenOrientation="landscape" android:launchMode="singleTask" 
        android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale" 
        android:name="com.google.cast.unityplugin.UnityPlayerActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
      </intent-filter>
      <meta-data android:name="com.google.cast.unityplugin.UnityPlayerActivity" android:value="true" />
    </activity>
  </application>
  <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="22" />
  <uses-feature android:glEsVersion="0x00020000" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>

Add an Audio Listener to the Unity Scene

To send audio to the remote display, we need an audio listener in the scene. We will use the CastRemoteDisplayAudioListener and disable all other audio listeners in the scene.

We need to add a script to ensure that the AudioListener is correctly persisted when the scene is restarted. Since the AudioListener object will persist across scenes, additional AudioListeners must be destroyed, which this component handles. Add a new script to the project in the Assets/Scripts folder by using the Unity editor Assets > Create > C# Script menu options. Name the script AudioListenerSingleton. Open the AudioListenerSingleton.cs file in an editor:

AudioListenerSingleton.cs

using UnityEngine;
using System.Collections;

public class AudioListenerSingleton : MonoBehaviour {

  private static AudioListenerSingleton instance = null;

  private void Awake() {
    if (instance && instance != this) {
      DestroyImmediate(gameObject);
      return;
    } else {
      instance = this;
      DontDestroyOnLoad(gameObject);
    }
  }
}

Now add the AudioListenerSingleton to the scene:

  1. Use GameObject > Create Empty to add a new object to the scene.
  2. Rename the empty object to AudioListenerSingleton.
  3. Add an Audio Listener component to the AudioListenerSingleton object.
  4. Add the Assets/Plugins/GoogleCastRemoteDisplay/Deprecated/CastRemoteDisplayAudioListener script to AudioListenerSingleton. You should see a CastRemoteDisplayAudioInterceptor automatically appear in addition to the CastRemoteDisplayAudioListener you just added.
  5. Add the Assets/Scripts/AudioListnerSingleton script to AudioListenerSingleton.

Add Remote Display to the Unity Scene

  1. Add the CastRemoteDisplayManager prefab from Assets/Plugins/GoogleCastRemoteDisplay to your scene hierarchy.
    This must be at the top level of your scene hierarchy.
  2. Select the CastRemoteDisplayManager in your hierarchy and for Cast App Id, enter Application Id you obtained from the Google Cast Developer Console.
  3. In the inspector, set the AudioListenerSingleton object you created in the previous section for the Remote Audio Listener.
  4. Add a new Camera to the scene using the GameObject > Camera menu options. Rename the camera to Mobile Camera. Point the camera at one of the walls. This will be the mobile background view while the game is casting (It is also possible to use a texture instead of a camera in your own game).
  5. Remove the Audio Listener component of the Mobile Camera.
  6. Remove the Audio Listener component of the Main Camera.
  1. Set the Remote Display Camera in the CastRemoteDisplayManager to the Mobile Camera.

We need a script to manage the cameras when the user Casts. Copy the RemoteCameraManager in the end_project Assets/Scripts/Camera project folder into the starter project Assets/Scripts/Camera folder. The script hooks into the CastRemoteDisplayManager events which will be explained later in this codelab.

Now hook up this script to the scene objects to make the remote camera work. We will use a script to switch the cameras when casting:

  1. Add the RemoteCameraManager script from Assets/Scripts/Camera script to the Mobile Camera object. Configure the script field values:

To add a simple pre-built UI to select a cast device, follow these steps:

You are now ready to run the game on your Android device:

Use the File menu to save the scene and save the project.

Frequently Asked Questions

It takes time to build the Android version of the game every time you want to test changes to your game. To speed up development we have a Remote Display simulator you can use within the Unity editor to select Cast devices and view the remote display.

To add the simulator to the project, follow these steps in the Unity editor:

  1. Add the CastRemoteDisplaySimulator prefab from Assets/Plugins/GoogleCastRemoteDisplay to your scene hierarchy.
    This must be at the top level of your scene hierachy.
  2. The Cast Devices section of the CastRemoteDisplaySimulator already has one virtual device by default. You can add additional devices (e.g. change Size to "2" and fill in dummy values for Device ID, Device Name, and Status).

Press the play button to run the scene within Unity and then press the Cast button in the top right corner to display the list of virtual Cast devices. The simulator is displayed in the bottom right of the scene. Press the Cast button again to disconnect.

Use the File menu to save the scene and save the project.

Frequently Asked Questions

The game will be controlled using two virtual joysticks:

The player can touch anywhere on the right side of the mobile screen to get the joystick that controls the gun and the player can touch anywhere on the left side of the screen to get the joystick that controls movement.

We need a script manage the touch events for the joysticks. Copy the TouchJoystick in the end_project Assets/MobileInput/Scripts project folder into the starter project Assets/MobileInput/Scripts folder. The script draws the graphics for the joysticks and tracks the directions of the touch events to control the player actions.

We also need 3 images that will be used to draw the joysticks. Copy the controllerFire.png, controllerRing.png and controllerWalk.png from the end_project Assets/MobileInput/Textures folder to your starter project Assets/MobileInput/Textures folder.

Let's add the two virtual joystick controls to the scene:

  1. Use the Unity editor GameObject > UI > Canvas menu options to add a new Canvas to the top level scene hierarchy.
  2. Rename the canvas to Joysticks.
  3. Change the Canvas Render Mode to Screen Space - Camera and change the Order in Layer to 2.
  4. Use the Unity editor GameObject > UI > Image menu options to add a new Image to Joysticks.
  5. Rename the image to WalkController.
  6. Change the Rect Transform to stretch horizontally and vertically. Set the Anchors / Max / X to 0.5. This will ensure this joystick is only available on the left side of the screen Reset the Right value to 0.
  7. Change the Image / Color / Alpha value to 0.
  8. Add Assets/MobileInput/Scripts/TouchJoystick to WalkController.
  9. Set the Touch Joystick Joystick Texture to Assets/MobileInput/Textures/controllerWalk.
  10. Set the Touch Joystick Ring Texture to Assets/MobileInput/Textures/controllerRing.
  11. Use the Unity editor GameObject > UI > Image menu options to add a new image to Joysticks.
  12. Rename the image to FireController.
  13. Change the Rect Transform to stretch horizontally and vertically. Set the Anchors / Min / X to 0.5. Reset the Left value to 0. This will ensure this joystick is only available on the right side of the screen.
  14. Change the Image / Color / Alpha value to 0.
  15. Add Assets/MobileInput/Scripts/TouchJoystick to FireController.
  16. Set the Touch Joystick Joystick Texture to Assets/MobileInput/Textures/controllerFire.
  17. Set the Touch Joystick Ring Texture to Assets/MobileInput/Textures/controllerRing.
  18. Set the Touch Joystick / Horizontal Axis Name to Mouse X.
  19. Set the Touch Joystick / Vertical Axis Name to Mouse Y.

It is important to set the sort order for the various parts of the UI. For example, the Cast button should be ordered above the joysticks such that if the user touches the Cast icon, that touch event goes to the button and not to the joysticks:

  1. Select CastDefaultUI in the scene hierarchy.
  2. Set the Canvas / Sort Order to 10
  3. Select MenuCanvas in the scene hierarchy (for the Pause dialog).
  4. Set the Canvas / Sort Order to 9.

Now build and run the game on your mobile device. When you touch the mobile screen you should see the joystick controls. Try and move around and kill the enemies. Click on the Cast button and use the same controls to play the game on the TV. Disconnect from the Cast device and then use the back system button to show the Pause dialog to quit the game.

Use the File menu to save the scene and save the project.

Frequently Asked Questions

We are going to customize the UI by changing the layout and colors of various objects in the game and in the plugin.

Firstly, let's remove the Pause panel "Quit Game" button since that was designed for desktop apps:

  1. Delete MenuCanvas / PausePanel / QuitButton in the scene.
  2. Select MenuCanvas / PausePanel / ResumeButton and center the button:

To make the pause dialog scale correctly for a mobile screen:

  1. Select MenuCanvas in the scene hierarchy.
  2. Add a Canvas Scaler component in the inspector.
  3. Change the Ui Scale Mode to Scale With Screen Size and keep the default settings.

To make the HUD UI scale correctly for a mobile screen:

  1. Select HUDCanvas in the scene hierarchy.
  2. Add a Canvas Scaler component.
  3. Change the Ui Scale Mode to Scale With Screen Size.

To customize the UI for each item in the Cast dialog list of devices:

  1. Add CastListElement from Assets/Plugins/GoogleCastRemoteDisplay/UI to the your scene hierarchy.
  2. Change the name to CustomCastListElement.
  3. Select CustomCastListElement in the project hierarchy and change the Image Color to "3B365CFF" in the inspector.
  4. Select CastDefaultUI/CastListDialog in the project hierarchy.
  5. Change the Cast List Dialog/List Element Prefab to your CustomCastListElement in the project hierarchy.

The Cast icon has a background but we want to make it transparent. To change the display of the Cast icon:

  1. Select CastDefaultUI/CastButtonFrame in the project hierarchy.
  2. Change the Image Color to "FFFFFF00" using the inspector to make the icon background transparent.
  3. Select CastDefaultUI/CastButtonFrame/CastButton in the project hierarchy,
  4. Change the width to 50 and height to 41 of the Rect Transform.

Build and run the game and take a look at the UI changes: device list items colors, larger Pause dialog and transparent background for the Cast icon.

Use the File menu to save the scene and save the project.

Frequently Asked Questions

When the game is casting we do not want to fatigue the player by making them constantly look up and down between the mobile screen and the TV. We want to use the mobile device mostly as a controller and the TV for visual feedback.

Currently the health and score is only displayed on the mobile screen. We need to move those to the remote display when the user is Casting:

  1. Select the HUDCanvas in the scene hierarchy.
  2. Change the Canvas / Render Mode to World Space.
  3. Change the Rect Transform values:
  1. Set the Canvas / Event Camera to the Main Camera.
  2. Add Assets/Scripts/Camera/CameraFollow as a script component.
  3. Set the CameraFollow / Target to the Main Camera.
  4. Set the CameraFollow / Smoothing to 0.

The remote display HUD is a bit dark, so let's tweak the lighting:

  1. Select Main Camera in the scene hierarchy.
  2. Open Vignette And Chromatic Aberration in the Inspector.
  3. Change the Vignetting value to 3.

We need to modify some existing script to support the HUD on the TV. Firstly, edit the Assets/ Scripts/Camera/CameraFollow script to support a zero smoothing value:

CameraFollow.cs

void FixedUpdate () {
  if (target != null) {
    Vector3 targetCamPos = target.position + offset;

    if (smoothing == 0) {
      transform.position = targetCamPos;
    } else {
      transform.position = Vector3.Lerp(transform.position, targetCamPos,   
          smoothing * Time.deltaTime);
    }
  }
}

When the game ends we want to display a game over text message on both the TV and the mobile screen. Edit the Assets / Scripts / Managers / GameOverManager script to control the mobile and TV UI's when the game ends:

GameOverManager.cs

using UnityEngine;
using Google.Cast.RemoteDisplay;

namespace CompleteProject {
  public class GameOverManager : MonoBehaviour {
    public PlayerHealth playerHealth;
    public GameObject gameOverButtonCanvas;

    void Start() {
      gameOverButtonCanvas.SetActive(false);
    }

    void Update () {
      if(playerHealth.currentHealth <= 0) {
        GetComponent<Animator>().SetTrigger("GameOver");
        if (CastRemoteDisplayManager.GetInstance().IsCasting()) {
          gameOverButtonCanvas.SetActive(true);
          gameOverButtonCanvas.GetComponent<Animator>()
              .SetTrigger("GameOver");
        }
      }
    }
  }
}

We will use the HUDCanvas GameOverText to display the TV text. We need to add a new canvas to display the mobile text. Add a new UI canvas for the mobile game over screen:

  1. Use the GameObject / UI / Canvas menu options to add a new canvas to the top level scene hierarchy.
  2. Rename the canvas to GameOverButtonCanvas.
  3. Change the Canvas Scaler / Ui Scale Mode to Scale With Screen Size.
  4. Add an Animator component to animate the text.
  5. Set the Animator / Controller to Assets > Animation > HUDCanvas.
  6. Add Assets > Scripts > Camera > CameraFollow as a script component to GameOverButtonCanvas.
  7. Set the CameraFollow / Target to the Main Camera.
  8. Set the CameraFollow / Smoothing to 0.
  9. Select GameOverButtonCanvas and add a Image that will be used as a darkened background.
  10. Rename the Image to BackgroundImage.
  11. Change the Background Image / Color to "00000085".
  12. Select GameOverButtonCanvas and add a Text.
  13. Rename the Text to GameOverText.
  14. Change the GameOverText Rect Transform values to match these:
  15. Change the Text / Text value to "Game Over!" and change the Character and Paragraph settings to match these:
  16. Set the HUDCanvas / Game Over Manager / Game Over Button Canvas to the GameOverButtonCanvas.

Build and run the game. Click on the Cast button to see the TV UI with the score and health indicator. The mobile app will show the joystick controllers. When the game ends, you should see the "Game Over" text on both the TV and the mobile device. Click on the Cast button to disconnect and the mobile UI will now show the score, health and joystick UI elements.

Use the File menu to save the scene and save the project.

Frequently Asked Questions

The Google Cast Remote Display plugin provides an API that Unity games can use to get informed about Cast devices and to control the remote display. We are going to use the API to control the visibility of a pause button during gameplay.

To add a pause button in the UI:

  1. Select MenuCanvas in the scene hierarchy.
  2. Enable the Canvas.
  3. Set the Canvas Sort Order to 9 (to ensure the Cast dialog can be displayed above the Pause dialog).
  4. Disable the Pause Manager script (we will use our own script to manage the pause button states)
  5. Use the Unity editor menu GameObject > UI > Button options to add a button to MenuCanvas.
  6. Rename the button to PauseButton.
  7. Delete the Text child object of the PauseButton.
  8. Change the Rect Transform / Anchor Presets of PauseButton to top/right:
  9. Set the Rect Transform / Pos X to -60, Pos Y to -60, Width to 50, Height to 50.
  10. Change the Image / Source Image to the PauseIcon from Assets/Plugins/GoogleCastRemoteDisplay/UI/Resources.

We need to add a script to manage the visibility of the pause button, Cast icon and joystick controls. Add a new script to the project in the Assets/Scripts folder by using the Unity editor Assets > Create > C# Script menu options. Name the script UIController. Open the UIController.cs file in an editor. Add the namespace and the following variables:

UIController.cs

using UnityEngine;
using System.Collections;
using Google.Cast.RemoteDisplay;

namespace CompleteProject {
  public class UIController : MonoBehaviour {

    public PlayerHealth playerHealth;
    public GameObject pauseButton;
    public GameObject pausePanel;

    private GameObject castUIController;
    private bool gameOver = false;
    private CastRemoteDisplayManager displayManager;
  
    // Use this for initialization
    void Start () {        
    }        
  
    // Update is called once per frame
    void Update () {        
    }
  }
}

The CastRemoteDisplayManager is a singleton and is the entry point for interacting with the native implementation of Google Cast Remote Display API. We will use the GetInstance method to get a reference to the singleton. The CastRemoteDisplayManager publishes various events:

Modify the Start method to initialize the UI state and hook into the Remote Display events:

UIController.cs

void Start () {
  displayManager = CastRemoteDisplayManager.GetInstance();
  displayManager.RemoteDisplaySessionStartEvent
     .AddListener(OnRemoteDisplaySessionStart);
  displayManager.RemoteDisplaySessionEndEvent
      .AddListener(OnRemoteDisplaySessionEnd);
  displayManager.RemoteDisplayErrorEvent
    .AddListener(OnRemoteDisplayError);
  castUIController = GameObject.Find("CastDefaultUI");
  pausePanel.SetActive(false);
  pauseButton.SetActive(false);
  if (displayManager.IsCasting()) {
    pauseButton.SetActive(true);
  }
}

public void OnRemoteDisplaySessionStart(CastRemoteDisplayManager manager) {
  castUIController.SetActive(false);
  pauseButton.SetActive(true);
}

public void OnRemoteDisplaySessionEnd(CastRemoteDisplayManager manager) {
  castUIController.SetActive(true);
  pauseButton.SetActive(false);
}

public void OnRemoteDisplayError(CastRemoteDisplayManager manager) {
  castUIController.SetActive(true);
  pauseButton.SetActive(false);
}

Modify the Update method to track the player health:

UIController.cs

void Update () {
  if (!gameOver && playerHealth.currentHealth <= 0) {
    gameOver = true;
    EndGame();
  }
}

Add the following methods to manage the game state and to restart the game level:

UIController.cs

public void StartGame() {
  Time.timeScale = 1f;
  castUIController.SetActive(false);
}

public void PauseGame() {
  pauseButton.SetActive(false);
  pausePanel.SetActive(true);
  castUIController.SetActive(true);
  Time.timeScale = 0f;
}

public void UnpauseGame() {
  pauseButton.SetActive(true);
  pausePanel.SetActive(false);
  castUIController.SetActive(false);
  Time.timeScale = 1f;
}

public void EndGame() {
  pauseButton.SetActive(false);
}

public void RestartLevel() {
  castUIController.SetActive(true);
  Application.LoadLevel(Application.loadedLevel);
}

Now add the UIController script to the scene:

  1. Select MenuCanvas in the scene hierarchy.
  2. Add the UIController script in the inspector.
  3. For the UI Controller script set the following values:

The MenuCanvas Inspector should now look like this:

Modify the MenuCanvas/PausePanel/PauseButton Button OnClick handler to invoke the MenuCanvas UIController.UnpauseGame method.

Modify the existing PausePanel UI elements to use the UIController script methods:

  1. Select MenuCanvas/PausePanel/ResumeButton in the scene hierarchy.
  2. Modify the Button OnClick handler to invoke the MenuCanvas UIController.UnpauseGame method.
  3. Remove the second OnClick handler by selecting it and clicking on the "-" button.

Save the scene and the project. Build and run the game on your mobile device. When you click on the Cast button and select a Cast device, the game will start and the mobile screen will display the pause icon. Click on the pause icon to see the pause dialog. Click on the Resume button to resume the game or click on the Quit Game button to stop the game.

Frequently Asked Questions

The sample game is now using the Google Cast Remote Display plugin for Unity! The UI supports the Cast button and has joystick controls to play the game on your TV.

What we've covered

Next Steps

Learn More