Time to turn our boring button into something interactive!
In this lesson, you’ll write your first real game logic in Unity:
👉 When a player clicks a button → increase a counter → update the UI text.
Let’s click like it’s 1999.
🧰 Step 1: Create the Script
- Right-click in the Project window → Create → C# Script
- Name it
ClickCounter
- Drag it onto any GameObject in your scene (like an empty object called
GameManager
)
💻 Step 2: Write the Click Logic
Open ClickCounter.cs
and replace the code with:
using TMPro;
using UnityEngine;
public class ClickCounter : MonoBehaviour
{
public int clickCount = 0;
public TextMeshProUGUI clickText;
public void CountClick()
{
clickCount++;
clickText.text = "Clicks: " + clickCount;
}
}
Let’s break it down:
clickCount
keeps track of how many times you’ve clickedclickText
is the UI label we updateCountClick()
is the method that runs when the button is pressed
🧪 Step 3: Hook Up the Button
- Select the Click Button in the Hierarchy
- In the Inspector, scroll to the Button (Script) component
- Under On Click(), click the
+
icon - Drag the GameObject with your
ClickCounter
script into the slot - From the dropdown, choose →
ClickCounter → CountClick()
Now the button knows what function to run when clicked!
🔗 Step 4: Link the Text Label
Select the GameObject with your ClickCounter
script and in the Inspector:
- Drag your
ClickCountText
UI element into the Click Text field
This connects the script to the visual label. 🧠
🧪 Test It!
- Hit Play
- Click the button
- Watch the counter go up!
Congrats — you just made a working clicker mechanic! 🎉
🧠 Recap
- Created a script with a public method
- Connected that method to a UI button
- Updated a text label from code
- Built your first working game mechanic 🔥
🧪 Mini Challenge: Customize It!
- Add sound or animation when the button is clicked
- Let the player earn 2 points per click (instead of 1)
- Change the text color once they reach 10 clicks
- Add a “Reset” button that sets the count to 0
🚀 What’s Next?
Let’s take that UI to the next level and make it dynamic and polished.
We’ll work on visual updates, better font effects, and auto-scaling.
🖼️ Go to Lesson 15 → Updating Text Dynamically in Unity