Creating a UI Button to reveal an image
In this recipe, we’ll create a button that, when pressed, will make an image appear.
Getting ready
For this recipe, we have prepared the image that you need in a folder named Images
in the 02_01
folder.
How to do it...
To create a UI Button to reveal an image, follow these steps:
- Create a new Unity 2D project.
- Import the unity_logo image into the Project folder.
- Drag the unity_logo image into the scene and in the Inspector panel, set the scale property to X 2 Y 2, and uncheck the check box as per the screenshot to make this GameObject inactive. An inactive GameObject is not displayed, and nor does it have any active behavior (so no scripts run and it does not respond to any event messages).
- Load the TextMeshPro Essential Resources, by choosing Window | TextMeshPro | Import TMP Essential Resources.
Figure 2.3: Inspector properties for an image in the scene
- In the Hierarchy window, right-click and select Create | UI | Button-TextMeshPro.
- Select GameObject Button in the Hierarchy window and click on the plus (+) button at the bottom of the Inspector window, to create a new OnClick event handler.
- Drag the unity_logo image from the Hierarchy window over the Object slot immediately below the menu that says Runtime Only.
- Select the SetActive (bool) method from the GameObject drop-down list (initially showing No Function) and click on the checkbox.
Figure 2.4: Settings for the OnClick event handler for the button
- Save your changes and run the scene. When you click the button, the image will appear.
How it works...
In this recipe, you created a new scene, imported an image, and unchecked the Visible in Runtime checkbox for the image so that it would not be seen at runtime.
You added a UI Button and a new OnClick event action that executes the GameObject.SetActive() method of the GameObject drop-down list of the button, and you checked the box so that the image (unity_logo
) appears when the button is clicked.
There’s more...
As an alternative to having the image appear when clicking on a button, the same button could be used to make an image disappear by the checkbox on the image.