这里给大家一个通用的提示或警告窗口的框架
首先先创建一个警告的Model类(不用继承MonoBehaviour)WarningModel
- using UnityEngine;
- using System.Collections;
- //声明一个警告委托 用于在弹出警告的同时运行其他程序的方法
- public delegate void WarningResult();
- public class WarningModel {
- //声明该方法委托
- public WarningResult result;
- //需要显示的文字
- public string value;
- //延迟多久自动关闭
- public float delay;
- //警告模型
- public WarningModel(string value,WarningResult result=null,float delay=-1)
- {
- this.value=value;
- this.result=result;
- this.delay=delay;
- }
- }
接着再创建一个警告的UI窗口,创建一个WarningWindow脚本拖给该窗口,并将自身的子物体UILabel(NGUI)或Text(UGUI),拖到检视窗口,然后拖成预制体
- using System.Collections;
- public class WarningWindow : MonoBehaviour {
- [SerializeField]
- private UILabel text; //NGUI
- //private Text text; //UGUI
- //用于接收model的result方法
- WarningResult result;
- //使Window显示出来 如果有需要延迟消失 就delay后消失
- public void active(WarningModel value)
- {
- text.text=value.value;
- this.result=value.result;
- //如果WarningModel设置了延迟时间
- if(value.delay>0)
- {
- //delay时间后执行close函数
- Invoke("close",value.delay);
- }
- gameObject.SetActive(true);
- }
- //关闭Window 如果有需要运行的方法就运行
- public void close()
- {
- //close函数是否正待等候调用 很明显他已经调用了 现在要删除它
- if(IsInvoking("close"))
- {
- //取消调用
- CancelInvoke("close");
- }
- gameObject.SetActive(false);
- //看看是否有需要执行的函数
- if(result!=null)
- {
- result();
- }
- }
- }
创建WarningManager脚本,挂载在一个一直存在的物体上(比如:摄像机)
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- public class WarningManager : MonoBehaviour {
- //存放所有警告Model的列表
- public static List<WarningModel> errors=new List<WarningModel> ();
- [SerializeField]
- private WarningWindow window; //警告窗口
- void Update()
- {
- if(errors.Count>0)
- {
- //取出列表的第一个
- WarningModel err=errors[0];
- //然后删除
- errors.RemoveAt(0);
- //最后显示
- window.active(err);
- }
- }
- }
如果想要在其他窗口重用,将创建的预制体拖到Canvas(UGUI)或UI Root(NGUI)下,然后将WarningManager 拖给一个一直存在的物体上(比如:摄像机)
如果想要显示警告窗口,就在代码中使用
- WarningManager.errors.Add(new WarningModel("你的金币已为0,恭喜,又变成了屌丝!"));