问题描述:如果我们想实现在一个倒计时结束后可以执行某个方法,比如挑战成功或者挑战失败,或者其他什么的比如生成boss之类的功能,而且你又不想每次都把代码复制一遍,那么就可以用下面这种方法。
结构
实现步骤
创建一个这样的结构(一个图片CountdownManage,两个文本Tips,countdown)
编写脚本CountdownManage并拖到CountdownManage图片上
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;public class CountdownManage : MonoBehaviour
{public static CountdownManage instance;private Action Dosomething;void Awake(){if (instance == null){instance = this;}else{Destroy(gameObject);}}public void ShowCountdown(string tips, int time, Action dosomething){gameObject.SetActive(true);Dosomething += dosomething;//添加委托gameObject.transform.Find("Tips").GetComponent<Text>().text = tips;StartCoroutine(Countdown(time));}IEnumerator Countdown(int time){while (time > 0){gameObject.transform.Find("countdown").GetComponent<Text>().text = time.ToString();time--;yield return new WaitForSeconds(1);}Dosomething?.Invoke();gameObject.SetActive(false);Dosomething = null;//清空委托}
}
创建一个空对象并编写脚本TextCountdown ,将脚本加到空对象上
using UnityEngine;public class TextCountdown : MonoBehaviour {void Update(){if (Input.GetKeyDown(KeyCode.Space)) {CountdownManage.instance.ShowCountdown("空格按下的倒计时", 6, SpaceCountdown);}if (Input.GetKeyDown(KeyCode.E)){CountdownManage.instance.ShowCountdown("E按下的倒计时", 10, ECountdown);}}void SpaceCountdown(){Debug.Log("空格按下");}void ECountdown(){Debug.Log("F1按下");} }
运行游戏按下空格就会出现对应的倒计时,倒计时结束后就会打印对应的调用方。(倒计时结束后按下E就会进入新的倒计时)
如果这篇文章对你有帮助可以点个赞哦!