概要
前回の続きです。
今回はaボタンを押すと敵のHPが減少する処理を実装します。
以下gifアニメはキーボードのaボタンを二回押したときの様子です。
次へ
開発環境
IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10
UnityEditor上の設定
HPバー
EnemyHealthContainerスクリプトをアタッチします。
実装のポイント
新規にEnemyHealthContainerクラスを作成します。
役割としては、HPバーのImageオブジェクトをEnemyObjectにアタッチされているEnemyHealthクラスに渡すことです。
EnemyHealthクラスはaボタンを押した時にHPが減る処理を追加します。
UI的にはImage.fillAmountを使ってHPの減少を表現しています。
コード部分
EnemyHealthContainer.cs
using UnityEngine;
using UnityEngine.UI;
public class EnemyHealthContainer : MonoBehaviour
{
[SerializeField] private Image fillAmountImage;
public Image FillAmountImage => fillAmountImage;
}
EnemyHealth.cs
using System.Collections;
using System.Collections.Generic;
+ using System.ComponentModel;
using UnityEngine;
+ using UnityEngine.UI;
public class EnemyHealth : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] private GameObject healthBarPrefab;
[SerializeField] private Transform barPosition;
[SerializeField] private float initialHealth = 10f;
[SerializeField] private float maxHealth = 10f;
+ public float CurrentHealth { get; set; }
+ private Image _healthBar;
void Start()
{
CreateHealthBar();
+ CurrentHealth = initialHealth;
}
+ private void Update()
+ {
+ if (Input.GetKeyDown(KeyCode.A))
+ {
+ DealDamage(5f);
+ }
+
+ _healthBar.fillAmount = Mathf.Lerp(_healthBar.fillAmount, CurrentHealth / maxHealth, Time.deltaTime * 10f);
+ }
private void CreateHealthBar()
{
GameObject newBar = Instantiate(healthBarPrefab,barPosition.position,Quaternion.identity);
newBar.transform.SetParent(transform);
+ EnemyHealthContainer container = newBar.GetComponent<EnemyHealthContainer>();
+ _healthBar = container.FillAmountImage;
}
+ public void DealDamage(float damageReceived)
+ {
+ CurrentHealth -= damageReceived;
+ }
}
参考
fillAmount
ラムダ式
Section4 16
github コミット分
章まとめ