程序设计基础
登录
< 返回教程列表

3.6 Unity 常用 API 综合例题

例题:完整的血条、UI 交互示例

using UnityEngine;
using UnityEngine.UI;

public class PlayerHpUI : MonoBehaviour
{
    public int maxHp = 100;
    public int currentHp;
    public Image hpBar;   // UI 里拖一个 Slider 的 Fill 区域 或 Image(Image Type = Filled)

    private void Start()
    {
        currentHp = maxHp;
        UpdateHpBar();
    }

    // 扣血
    public void TakeDamage(int dmg)
    {
        currentHp -= dmg;
        if (currentHp < 0) currentHp = 0;
        UpdateHpBar();
        if (currentHp == 0) Die();
    }

    // 加血
    public void Heal(int amount)
    {
        currentHp += amount;
        if (currentHp > maxHp) currentHp = maxHp;
        UpdateHpBar();
    }

    private void UpdateHpBar()
    {
        if (hpBar != null)
            hpBar.fillAmount = (float)currentHp / maxHp;
    }

    private void Die()
    {
        Debug.Log("玩家死亡");
        // 可以播放死亡动画、禁用控制等
    }
}

练习题(综合)

  1. 做一个"打地鼠"雏形:场景随机生成 9 个位置,每 2 秒有一个位置从地下冒出一个 Cube(地鼠),玩家点击地鼠用 OnMouseDown 销毁得 10 分,地鼠 1.5 秒未被点自动消失。

  2. 做一个简单 FPS:WASD 移动、鼠标视角、空格跳、按左键发射 ray 射线打靶子(Physics.Raycast),打到靶子分数+10。

  3. 做一个"金币收集大冒险":场景散落 10 个金币(Tag=Coin),玩家拾取后计数+1;加一个"敌人"在巡逻,玩家被敌人撞到扣 20 血;当金币全部集齐,显示"通关";当血为 0,显示"失败"。