Introduction to Unity UI – Part 3

In this final part of our three part tutorial series, you’ll learn how to integrate Unity UI into a working game. By Brian Moakley.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Displaying the Restart Dialog

You’re not going to animate the appearance of the dialog. Instead, you’ll just hide the dialog at the start and show it when the player loses the game.

Open the MouseController script in a code editor and add the following instance variable:

public GameObject restartDialog; 

Then add following line of code toStart() to hide the dialog at the start:

restartDialog.SetActive(false);

Scroll down and add following line to the end of HitByLaser():

restartDialog.SetActive(true);

As you probably guessed, HitByLaser() is called when the mouse dies. Hence, it’s the perfect place to display a restart dialog.

Add the following two methods to restart and exit the game:

public void RestartGame() 
{
    Application.LoadLevel (Application.loadedLevelName);
}
    
public void ExitToMenu() 
{
    Application.LoadLevel ("MenuScene");
}

You’ll link them to the corresponding buttons in a moment.

Save the script file and switch back to Unity.

In Unity, select Mouse in the Hierarchy and drag Dlg_Restart to the Restart Dialog field in the Inspector.

36

Then select Btn_Restart in the Hierarchy and scroll down to the On Click (Button) list.

Click + to add a new item. After that, drag Mouse from the Hierarchy to the new item. In the function selection dropdown, select MouseController \ RestartGame ().

37

Now, select Btn_Exit, and repeat the process, but this time select the MouseController \ ExitToMenu () function.

Save the scene to save your work then run the scene and send your mouse into the laser’s line of fire. You should see a dialog appear instantly after he dies. If you press Restart, you’ll restart the game. If you press Exit you’ll return to the main menu.

38

And once again I’m ending a tutorial on a high note — with an image of the poor, lifeless mouse. Sorry, no kittens today, maybe in the next series. :]

Where To Go From Here?

Congratulations on completing this tutorial! You can download the final project here: Rocket Mouse Starter Project

I hope you like the UI system and are excited to create some cool user interfaces in your games! Surely, the prospect of minimal coding alone should have you feeling a bit gleeful.

If you create some awesome control using the UI system, we’d all love to see your handiwork. Go ahead and post a screenshot, video or GIF animation in comments to show the world your awesome new skills — and maybe inspire a fellow dev or few (or make them jealous). :]

If you have any questions or comments, please leave them below. I will be happy to answer!

Good luck!