我们经常会用到弹窗,弹窗的重复使用也比较多,所以我们需要更好的管理方式,才能有效的使用它。
首先我们要创建弹窗预设体,因为不同的弹窗 按钮数量会不一样,所以我们要做好按钮的排版。
脚本区域:
添加ConfirmDialog.ts挂载到预设体上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
using UnityEngine; using System.Collections; using UnityEngine.UI; using System; /// <summary> /// 确认对话框 /// </summary> public class ConfirmDialog : MonoBehaviour { [SerializeField] Text m_Label; [SerializeField] Button m_Yes; [SerializeField] Button m_No; void Awake() { m_Yes.onClick.AddListener(OnYes); // 添加点击监听事件 m_No.onClick.AddListener(OnNo); } /// <summary> /// 确定事件 /// </summary> private void OnYes() { m_Callback(ConfirmTypeDef.Yes); Destroy(gameObject); } /// <summary> /// 取消事件 /// </summary> private void OnNo() { m_Callback(ConfirmTypeDef.No); Destroy(gameObject); } Action<ConfirmTypeDef> m_Callback; public void Init(string msg, Action<ConfirmTypeDef> callback, ConfirmTypeDef button = ConfirmTypeDef.Yes | ConfirmTypeDef.No) { Debug.Assert(callback != null); m_Label.text = msg; m_Callback = callback; if (0 == (button & ConfirmTypeDef.No)) { m_No.gameObject.SetActive(false); } } /// <summary> /// 设置父对象 /// </summary> /// <param name="parent"></param> public void SetParent(Transform parent) { transform.SetParent(parent, false); } /// <summary> /// 设置参数 /// </summary> /// <param name="pos"></param> /// <param name="scale"></param> /// <param name="rot"></param> public void SetLocal(Vector3 pos, Vector3 scale, Quaternion rot) { transform.localPosition = pos; transform.localScale = scale; transform.localRotation = rot; } /// <summary> /// 创建物体 /// </summary> /// <returns></returns> public static GameObject Create() { GameObject go = Resources.Load("ConfirmDialog") as GameObject; return Instantiate(go) as GameObject; } } [Flags] public enum ConfirmTypeDef { None = 0, //没有按钮 Yes = 1, //确定 No = 2, //拒绝 } |
创建Test.ts脚本到摄像机,然后运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using UnityEngine; using System.Collections; public class Test : MonoBehaviour { // Use this for initialization void Start() { GameObject go = ConfirmDialog.Create(); ConfirmDialog cd = go.GetComponent<ConfirmDialog>(); cd.SetLocal(Vector3.zero, Vector3.one, Quaternion.identity); cd.Init("是否确认退出", (button) => { if (button == ConfirmTypeDef.Yes) { Yes(); } //else if (button == ConfirmTypeDef.No) //{ // No(); //} }, ConfirmTypeDef.Yes); // 最后参数是显示的按钮 多个按|隔开 } void Yes () { Debug.Log("Yes"); } void No () { Debug.Log("No"); } } |
- 本文固定链接: http://www.u3d8.com/?p=613
- 转载请注明: 网虫虫 在 u3d8.com 发表过