首先是效果展示:
另外圆环型冷却条效果也是大同小异,如有需要可以关注作者了解下一篇文章。这里就不赘述。。
注:写这篇文章主要是记录自己,同时也为有需要的朋友借鉴,如有不理解或者不足之处还请读者能够发消息指正。感谢,感谢。。。。。
下面为主要灰色圆形冷却效果介绍
实现这个功能关键是了解图片的填充方式,在按钮上添加一个image,名字为coolingimg,其图片是圆形颜色改为灰色,然后通过计时控制 image组件下的 Fill Amount参数来实现。
Hierarchy下按钮结构。reload是一个按钮,buttonimg为按钮图片,coolingimg为冷却填充图片。
reload按钮下coolingimg 的Inspector属性界面:
reload按钮 ,Inspector属性界面。脚本挂载此处。
脚本详情如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Coolingtime : MonoBehaviour
{
// Start is called before the first frame update
public GameObject player;
private Animator Anim;//动画
private float currentTime; //
private Image coolingImage;
private float coolingTimer;
public GameObject fire;
public GameObject button;
public int magazinenum;//子弹数
public int currnum;//当前子弹数
public Text magazine;
private string magazinevalue;
public int weapon;
// Use this for initialization
void Start()
{
coolingImage = transform.GetChild(1).GetComponent<Image>();//获取需要冷却的灰色图片
coolingImage.raycastTarget = false;//内存优化
coolingImage.fillAmount = 0.0f;//初始化零填充冷却图片,点击按钮后才会出现
}
void Awake()
{
Anim = player.GetComponent<Animator>();//玩家动作动画
}
// Update is called once per frame
void Update()
{
weapon = button.GetComponent<WeaponControl>().weapon;//获取玩家当前所持武器
Debug.Log(weapon);
UpdateImage();//填充图片
magazinevalue = currnum + "/" + magazinenum;//子弹数显示
magazine.text = magazinevalue;//子弹数显示
}
public void OnBtnClickSkill(float timer)//按钮点击事件,参数冷却时间
{
if(currnum > 0)//判断是否还有弹夹
{
//初始化按钮事件
currnum -= 1;
coolingTimer = timer;//冷却时间
currentTime = 0.0f;
coolingImage.fillAmount = 1.0f;//填充度
}
else
{
currnum = 0;
}
}
private void UpdateImage()//冷却图片填充
{
if (currentTime < coolingTimer)
{
currentTime += Time.deltaTime;//记录当前时间
coolingImage.fillAmount = 1 - currentTime / coolingTimer;//倒计时,填充度为1 - currentTime / coolingTimer;当前时间占比
if (coolingImage.fillAmount != 0)//
{
coolingImage.raycastTarget = true;
Anim.SetBool("Reload", true);//播放换弹动作
}
else//冷却后执行的事件
{
if (weapon == 0)//判断所持武器
{
fire.transform.gameObject.GetComponent<PlayerFire>().currnum = fire.transform.gameObject.GetComponent<PlayerFire>().cartridgenum;//换弹
Anim.SetBool("Reload", false);
}
else if (weapon == 1)
{
fire.transform.gameObject.GetComponent<PlayerFire>().pistolcurrnum = fire.transform.gameObject.GetComponent<PlayerFire>().pistolcartridgenum;
Anim.SetBool("Reload", false);
}
coolingImage.raycastTarget = false;
}
}
}
}