使用UI实时显示生命值
在Health中添加获取百分百的方法。随后编写一个脚本挂着UI上实时调用该方法
敌人生命值的显示也是一样,创建一个新脚本挂在敌人上
- public float GetPercentage()//返回生命值的百分比
- {
- //返回当前生命值 / 基础状态中的获取生命值
- return 100*healthPoints / GetComponent<BaseStats>().GetHealth();
- }
-
复制代码
HealthDisplay
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
-
- namespace RPG.Resources
- {
- //
- public class HealthDisplay : MonoBehaviour
- {
- Health health;
- Text healthDisplay;
-
- private void Awake()
- {
- health = GameObject.FindWithTag("Player").GetComponent<Health>();
- healthDisplay = GetComponent<Text>();
- }
-
- private void Update()
- {
- healthDisplay.text=string.Format("{0:0}%", health.GetPercentage());
- }
- }
- }
-
复制代码
EnemyHealthDisplay
- using RPG.Combat;
- using RPG.Resources;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
-
- namespace RPG.Resources
- {
- public class EnemyHealthDisplay : MonoBehaviour
- {
- Fighter fighter;
-
-
- private void Awake()
- {
- fighter = GameObject.FindWithTag("Player").GetComponent<Fighter>();
-
- }
-
- private void Update()
- {
- if(fighter.GetTarget() == null)
- {
- GetComponent<Text>().text = "N/A";
- }
- if(fighter.GetTarget() != null)
- {
- Health health = fighter.GetTarget();
- GetComponent<Text>().text = String.Format("{0:0}%", health.GetPercentage());
- }
-
- }
- }
- }
-
复制代码
|