Unity3D How To Create an easy UI Popup Window

Unity3D How To Create an easy UI Popup Window

I was creating a simple quiz game and needed a popup or modal window for after the player made a choice. The Unity3D tutorial page has an advanced and complicated method that was way more than I needed.

Here is a simpler solution that I created as an alternative:

Short Summary

Create a second canvas that you activate/de-activate at game time. When you activate the canvas, you’ll have it set to be on a higher/closer layer than your main canvas. Thus when you activate the second canvas, it covers the main canvas and requires the player to tap/click a button to continue. Then you detect the button click, deactivate the second canvas and the game continues.

Create A Second Canvas

In the inspector, create a second canvas, set layer or sort order to be over the primary canvas, add a UI button (this will act as the modal effect which forces the player to click it to continue), add text on the second canvas (information, game over etc.), and deactivate the second canvas so when the game starts it will only show when you call it.

Activate the Second Canvas

During game time, when you need the popup, find the canvas GameObject or have a public GameObject set in the Inspector. Now just set the active state of the second canvas to active and it will popup.

public GameObject mySecondCanvas;

public void myFunction() {
     mySecondCanvas.SetActive(true);
}

Wait For Button

Now that your popup window is on the game screen, you’ll need to code the button to act appropriately. Create a function for the button to deactivate the popup and the game can continue, an easy spot is in the same script as the above code.

public void OnClickButton(string choice) {
     if( choice == "continue") {
          mySecondCanvas.SetActive(false);
     }
}

In the Inspector, go into the second canvas structure, then into the button. Click the + symbol in the On Click() area in the Button component. Now drag your object that the above script is attached to, into the None (Object) slot under the “Runtime Only” dropdown, then use the button to browse and find your OnClickButton function and then type “continue” (no quotes) into the text area. Now when a player clicks the button it will send “continue” to the function and deactivate the popup.

Unity3D How To Create an easy UI Popup Window