using ui
If you want your UI counter to act as a score system, you’re already 90% of the way there. The structure is the same — you just change the meaning of the number and when it increases.
Let’s build a clean, flexible score system you can plug into your spawner, enemies, collectibles, or anything else.
🏆 1. Create a Score UI
Use TextMeshPro:
- GameObject → UI → Text (TMP)
- Rename it to ScoreText
- Place it wherever you want the score to appear
🧩 2. Score Manager Script
This keeps the score and updates the UI.
using UnityEngine;
using TMPro;
public class ScoreManager : MonoBehaviour
{
public TextMeshProUGUI scoreText;
private int score = 0;
void Start()
{
UpdateUI();
}
public void AddScore(int amount)
{
score += amount;
UpdateUI();
}
public void ResetScore()
{
score = 0;
UpdateUI();
}
void UpdateUI()
{
scoreText.text = "Score: " + score;
}
}
Attach this to a GameObject (like your Canvas), then drag your ScoreText into the scoreText field.
🎯 3. Add Score When Something Happens
You decide what counts as “score.” Here are common examples:
⭐ When an enemy is destroyed
public ScoreManager scoreManager;
void OnDestroy()
{
scoreManager.AddScore(10);
}
⭐ When a collectible is picked up
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
scoreManager.AddScore(1);
gameObject.SetActive(false);
}
}
⭐ When you spawn something (if your game rewards spawning)
scoreManager.AddScore(1);
🚀 4. Connect It to Your Spawner
If you want score to increase every time you spawn an object:
public ScoreManager scoreManager;
void Spawn()
{
GameObject obj = Instantiate(prefab, transform.position, Quaternion.identity);
scoreManager.AddScore(1);
}
Or with object pooling:
GameObject obj = pool.Get();
obj.transform.position = transform.position;
scoreManager.AddScore(1);
Comments