CodeBlanks Logo Icon CodeBlanks

Image and Button

Learn to make clickable UI elements with Image and Button.

Image component

The Image component renders 2D Sprite graphics (panels, health bars, icons) on a Canvas. Within a Canvas hierarchy, Image is used instead of the 3D world's SpriteRenderer.

// Creating a health bar by adjusting Image fillAmount
using UnityEngine.UI;
Image healthBar = GetComponent<Image>();
healthBar.fillAmount = 0.75f;

Setting Image Type to Filled allows the fillAmount property to drive circular cooldowns or horizontal progress bars.

Button and onClick event

The Button component is an interactive UI element capturing mouse clicks or touchscreen taps. To dictate what occurs upon a click, functions are registered to its onClick event.

// Binding a function to button click via code
Button playButton = GetComponent<Button>();
playButton.onClick.AddListener(StartGame);

This mechanism underpins all interactive actions like launching gameplay, opening menus, or advancing dialogue.

Practice Print button interaction

Assign "Button" to uiType and "StartGame" to action. Print UI: Button | Triggered: StartGame to the console.

Starter code

Player.cs
using System;

class Program
{
    static void Main()
    {
        // uiType ve action değerlerini tanımlayıp yazdır
    }
}

Sample solution

Player.cs
using System;

class Program
{
    static void Main()
    {
        string uiType = "Button";
        string action = "StartGame";
        Console.WriteLine("UI: " + uiType + " | Triggered: " + action);
    }
}

Expected output

UI: Button | Triggered: StartGame

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which event is used to listen to the exact moment a user clicks a UI Button component?

  • onHover
  • onTrigger
  • onRelease
  • onClick Correct answer

Explanation: onClick is the standard UnityEvent triggered whenever a Button component receives a click.

2 Attach click listener

Question
playButton.onClick.____(OnPlayClicked);
Answer
playButton.onClick.AddListener(OnPlayClicked);

Explanation: The AddListener method is invoked to register a function to a UnityEvent via code.

3 Image and Button fields

Term Meaning
Image Displays 2D sprite on Canvas
Button Receives user click interactions
onClick UnityEvent on button click
fillAmount Image fill ratio (0-1)

All lessons in Intermediate