参考:
Unity脚本的生命周期
C# 协程 在 Unity中的应用
[中文字幕]角色UI血条以及被击中后的“掉血”缓冲效果(包括:敌人简单AI-巡逻或射击)
用协程完成中毒需求
按下空格, 进入中毒, 立马扣除20血量, 每秒5滴血, 持续3秒
(务必看完参考)
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HpManger : MonoBehaviour
{
public Image hpImage;
public Image nhpImage;
public float hp;
[SerializeField]
public float maxHp;
[SerializeField]
public float speed = 0.005f;
// Start is called before the first frame update
void Start()
{
hp = maxHp;
}
// Update is called once per frame
void Update()
{
hpImage.fillAmount = hp / maxHp;
if (nhpImage.fillAmount > hpImage.fillAmount)
{
nhpImage.fillAmount -= speed;
}
else
{
nhpImage.fillAmount = hpImage.fillAmount;
}
if(Input.GetKeyDown(KeyCode.Q))
{
hp += 30;
if(hp >= maxHp)
{
hp = maxHp;
}
}
if(Input.GetKeyDown(KeyCode.Space))
{
hp -= 20;
StartCoroutine(PosionHp());
}
}
// 中毒 每秒5滴血 持续3秒
IEnumerator PosionHp()
{
Debug.Log("PosionHp 协程 start");
for(int i = 0; i < 3; i++)
{
yield return StartCoroutine(ReduceHp(5, 1));
}
Debug.Log("PosionHp 协程 end");
}
IEnumerator ReduceHp(int value, int second)
{
Debug.Log("ReduceHp 协程 start");
yield return new WaitForSeconds(second);
hp -= value;
}
}