Health System

This page describes how the Observed<T> class can be used to create a simple player health system.

One common use case for the Observed asset is creating a health system for a player character in a game. This guide will walk you through creating a player health script, a health display script, and a bullet script that damages the player.

Player Health Script

To manage the player's health, create a new script called "PlayerHealth". This script will have an observable variable that stores the player's health.

using Observed;
using UnityEngine;

public class PlayerHealth : MonoBehaviour
{
    public Observed<int> health = new Observed<int>(100); // Initialize health with 100
}

Health Display Script

Next, let's create a script that displays the player's health in the user interface. We will use a Text component to show the player's health as a string.

using UnityEngine;
using UnityEngine.UI;
using Observed;

public class HealthDisplay : MonoBehaviour
{
    public PlayerHealth playerHealth;
    public Text healthText;

    void Start()
    {
        playerHealth.health.Subscribe(UpdateHealthText); // Subscribe to changes in the player's health
    }

    void UpdateHealthText(int health)
    {
        healthText.text = $"Health: {health}"; // Update the UI when the player's health changes
    }
}

Bullet Script

Finally, create a "Bullet" script that will decrease the player's health whenever the bullet collides with a player.

using UnityEngine;

public class Bullet : MonoBehaviour
{
    public int damage = 10; // Amount of damage the bullet will deal

    private void OnCollisionEnter(Collision collision)
    {
        var player = collision.gameObject.GetComponent<PlayerHealth>();
        if (player != null)
        {
            player.health.Value -= damage; // Decrease the player's health
        }
    }
}

With these scripts, the bullet class simply decreases the player's health and the health display script updates the user interface automatically. This makes it easier to write and maintain your code.

Last updated