UI制作
一、加入Canvas
调整Canvas的Render Mode为World Space,Reset Rect Transform并根据个人要求调整其Width和Height。
二、制作宠物图标
在Canvas下添加一张宠物图片,并根据个人需求调整图片大小
根据个人需求选择宠物图片的位置,本文按住alt键选择右下角。
三、制作血条
首先在Canvas下创建一个空物体:HP作为后续血条图片的父物体(注意调整大小),随后在HP下创建三张图片:BG(空血背景),HPGreed(血量),HPRed(用作血量减少时展示消耗过程,可省略)。设置三张图片的内容以及大小位置。
将HPRed和HPGreed Image的Image Type改为Filled,随后将Filled Method改为Horizontal。
四、制作血量文字
在Canvas下新建Text,更改Scale,以显示文字,注意调整Text边框大小与文字大小。
代码控制血量变化
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UnitHPSlot : MonoBehaviour
{
public Text hp_text;
public Image hp_red;
public Image hp_green;
private UnitBasic unit;
private AttackManager attack_manager;
private float max_hp;
private float current_hp;
private void Awake()
{
unit = GetComponent<UnitBasic>();
attack_manager = AttackManager.Instance;
max_hp = unit.hp;
current_hp = unit.hp;
}
private void Start()
{
InitUnitHPSlot();
}
private void OnEnable()
{
attack_manager.HPChange += OnHPChange;
}
private void OnDisable()
{
attack_manager.HPChange -= OnHPChange;
}
private void Update()
{
//血量消耗效果
if(hp_red.fillAmount > hp_green.fillAmount)
hp_red.fillAmount -= Time.deltaTime;
}
//更新血量
public void Refresh()
{
current_hp = unit.hp;
hp_text.text = current_hp.ToString();
hp_green.fillAmount = current_hp / max_hp;
}
public void OnHPChange()
{
Refresh();
}
//初始化血量
public void InitUnitHPSlot()
{
hp_text.text = max_hp.ToString();
hp_red.fillAmount = current_hp / max_hp;
hp_green.fillAmount = current_hp / max_hp;
}
}