Unity提示消息窗口

发表于2018-04-25
评论0 2.5k浏览
很多游戏都会有需要弹框的场景,为了帮助大家,下面就和大家分享一个消息窗口提示的实现方法。

1.首先要有一个提示消息框的预制体。

2.本框架注意加载资源的地方需要改一下。
MessageBox
sing UnityEngine ;  
/// <summary>  
/// 通用对话框通用类  
/// </summary>  
public class MessageBox : MonoBehaviour  
{  
    public delegate void MessageDelegate( System.Object obj);  
    public MessageDelegate OkClick ;  
    public MessageDelegate CancelClick ;  
    private string customTextOK ;  
    public string TextOK  
    {  
        get { return textOK. text; }  
        set  
        {  
            textOK.text = value;  
            customTextOK = value ;  
        }  
    }  
    private string customTextCancel ;  
    public string TextCancel  
    {  
        get { return textCancel. text; }  
        set  
        {  
            textCancel.text = value;  
            customTextCancel = value ;  
        }  
    }  
    public int WidthOK  
    {  
        get { return widgetOK. width; }  
        set  
        {  
            widgetOK.width = value;  
        }  
    }  
    public int WidthCancel  
    {  
        get { return widgetCancel. width; }  
        set  
        {  
            widgetCancel.width = value;  
        }  
    }  
    public string Content  
    {  
        get { return content. text; }  
        set  
        {  
            content.text = value;  
        }  
    }  
    public int WitdhContent  
    {  
        get { return content. width; }  
        set  
        {  
            content.width = value;  
        }  
    }  
    public int StartingRenderQueue  
    {  
        get { return uiPanel. startingRenderQueue; }  
        set  
        {  
            uiPanel.startingRenderQueue = value;  
        }  
    }  
    public UIWidget.Pivot ContentPivot  
    {  
        get { return content. pivot; }  
        set  
        {  
            content.pivot = value;  
        }  
    }  
    // 延迟启用确定按钮  
    private float delayOkTime = 0;  
    public float DelayOkTime  
    {  
        get { return delayOkTime; }  
        set  
        {  
            delayOkTime = value ;  
        }  
    }  
    // 延迟启用取消按钮  
    private float delayCancelTime = 0;  
    public float DelayCancelTime  
    {  
        get { return delayCancelTime; }  
        set  
        {  
            delayCancelTime = value ;  
        }  
    }  
    public enum Type  
    {  
        OK,  
        OKCancel,  
        Custom1Btn,         // 自定义一个按钮  
        Custom2Btn,         // 自定义两个按钮  
    };  
    public Type type { get; private set; }  
    // 点背景是不是可以关闭对话框  
    public bool CanCloseByFadeBGClicked = true;  
    // 点击背景是否关闭对话框,只是关闭,不执行其他  
    public bool IsCloseByFadeBGClicked = false;  
    public System.Object userData { get; private set; }  
    private UIPanel uiPanel ;  
    private UISprite messageBoxBg ;  
    private UILabel content ;  
    public UIButton btnOK ;  
    private UILabel textOK ;  
    private UIWidget widgetOK ;  
    private UIButton btnCancel ;  
    private UILabel textCancel ;  
    private UIWidget widgetCancel ;  
    private GameObject fadeBG ;  
    void Awake()  
    {  
        this.transform .localPosition = new Vector3 (0, 0, -3200 + GameUIManager. UI_Z_OFFEST);  
        uiPanel = this .GetComponent< UIPanel>();  
        messageBoxBg = this .transform. FindChild("WinBG" ).GetComponent< UISprite>();  
        content = messageBoxBg .transform. FindChild("Content" ).GetComponent< UILabel>();  
        btnOK = messageBoxBg .transform. FindChild("OK" ).GetComponent< UIButton>();  
        textOK = btnOK .transform. FindChild("Label" ).GetComponent< UILabel>();  
        widgetOK = btnOK .transform. GetComponent<UIWidget >();  
        btnCancel = messageBoxBg .transform. FindChild("Cancel" ).GetComponent< UIButton>();  
        textCancel = btnCancel .transform. FindChild("Label" ).GetComponent< UILabel>();  
        widgetCancel = btnCancel .transform. GetComponent<UIWidget >();  
        fadeBG = this .transform. FindChild("FadeBG" ).gameObject;  
        UIEventListener.Get (btnOK.gameObject). onClick += this .OnOKClicked;  
        UIEventListener.Get (btnCancel. gameObject).onClick += this.OnCancelClicked;  
        UIEventListener.Get (fadeBG). onClick += this .OnFadeBGClicked;  
    }  
    void OnDisable()  
    {  
        OkClick = null ;  
        CancelClick = null ;  
        userData = null ;  
    }  
    void DestroySelf()  
    {  
        DestroyImmediate(this .gameObject);  
    }  
    protected void Close ()  
    {  
        btnOK.gameObject .collider. enabled = false ;  
        btnCancel.gameObject .collider. enabled = false ;  
        fadeBG.collider .enabled = false;  
        GameUITools.PlayCloseWindowAnim (messageBoxBg. transform, null , false);  
        // 自己维护自己的对象销毁时机,避免HOTween生命周期导致的回调函数没有被执行的问题  
        Invoke("DestroySelf" , 0.25f);  
    }  
    void Update()  
    {  
        if (delayOkTime > 0)  
        {  
            delayOkTime -= RealTime .deltaTime;  
            if (delayOkTime <= 0)  
            {  
                btnOK.isEnabled = true;  
                if (!string .IsNullOrEmpty( customTextOK))  
                {  
                    textOK.text = customTextOK;  
                }  
            }  
            else  
            {  
                btnOK.isEnabled = false;  
                 //这里显示倒计时本来是为了检测到加速器是显示倒计时,实际使用加速器之后倒计时也被加速了  
                if (!string .IsNullOrEmpty( customTextOK))  
                {  
                    textOK.text = string. Format("{0}({1})" , customTextOK, ( int)(delayOkTime + 1));  
                }  
            }  
        }  
        if (delayCancelTime > 0)  
        {  
            delayCancelTime -= RealTime .deltaTime;  
            if (delayCancelTime <= 0)  
            {  
                btnCancel.isEnabled = true;  
                if (!string .IsNullOrEmpty( customTextCancel))  
                {  
                    textCancel.text = customTextCancel;  
                }  
            }  
            else  
            {  
                btnCancel.isEnabled = false;  
                if (!string .IsNullOrEmpty( customTextCancel))  
                {  
                    textCancel.text = string. Format("{0}({1})" , customTextCancel, ( int)(delayOkTime + 1));  
                }  
            }  
        }  
    }  
    public void OnOKClicked (GameObject go)  
    {  
        if (Globals .Instance. GameMgr.Status != GameManager. EGameStatus.EGS_None )  
        {  
            Globals.Instance .EffectSoundMgr. Play("ui/ui_001" );  
        }  
        Close();  
        if (OkClick != null)  
        {  
            OkClick(userData );  
        }  
    }  
    public void OnFadeBGClicked (GameObject go)  
    {  
        if (CanCloseByFadeBGClicked )  
        {  
            OnCancelClicked(go );  
        }  
        else if (IsCloseByFadeBGClicked)  
        {  
            Close();  
        }  
    }  
    public void OnCancelClicked (GameObject go)  
    {  
        if (Globals .Instance. GameMgr.Status != GameManager. EGameStatus.EGS_None )  
        {  
            Globals.Instance .EffectSoundMgr. Play("ui/ui_002" );  
        }  
        Close();  
        if (CancelClick != null)  
        {  
            CancelClick(userData );  
        }  
    }  
    public MessageBox Show (string text, MessageBox .Type type, System. Object data )  
    {  
        gameObject.SetActive (true);  
        GameUITools.PlayOpenWindowAnim (messageBoxBg. transform, null , false);  
        content.text = text;  
        TextOK = StringManager .Instance. GetString("OK" );  
        TextCancel = StringManager .Instance. GetString("Cancel" );  
        bool isOnlyOneBtn = (type == Type.OK || type == MessageBox.Type .Custom1Btn);  
        Vector3 pos = btnOK.transform. localPosition;  
        pos.x = isOnlyOneBtn ? 0 : 90.5f;  
        btnOK.transform .localPosition = pos;  
        NGUITools.SetActive (btnCancel. gameObject, !isOnlyOneBtn );  
        OkClick = null ;  
        CancelClick = null ;  
        userData = data ;  
        delayOkTime = 0;  
        delayCancelTime = 0;  
        widgetOK.width = 83;  
        widgetCancel.width = 83;  
        btnOK.gameObject .collider. enabled = true ;  
        btnCancel.gameObject .collider. enabled = true ;  
        fadeBG.collider .enabled = true;  
        CancelInvoke("DestroySelf" );  
        if (Globals .Instance. TutorialMgr != null )  
        {  
            Globals.Instance .TutorialMgr. InitializationCompleted(this );  
        }  
        return this ;  
    }  
    public MessageBox Show (string text, MessageBox .Type type, Object userData, MessageDelegate OkCallback, MessageDelegate CancelCallback)  
    {  
        MessageBox msg = Show(text, type, userData);  
        this.OkClick = OkCallback;  
        this.CancelClick = CancelCallback;  
        return msg ;  
    }  
}

接着是他的父类:
using UnityEngine ;  
using System .Collections;  
/// <summary>  
/// 游戏中通用的确认框  
/// </summary>  
///  
public class GameMessageBox : MessageBox  
{  
    public static GameMessageBox Instance = null;  
    /// 通用弹出对话框接口  
    /// </summary>  
    /// <param name="content"> 提示文本</param>  
    /// <param name="type"> 按钮类型,决定按钮布局和显示的文字 </param>  
    /// <param name="userData"> 允许记录一个中间数据,给回调函数 </param>  
    /// <returns></returns>  
    public static GameMessageBox ShowMessageBox( string content , Type type, System. Object userData )  
    {  
        if (string .IsNullOrEmpty( content))  
        {  
            return null ;  
        }  
        if (Instance == null)  
        {  
            GameObject prefab = Res.LoadGUI( "GUI/MessageBox");  
            if (prefab == null)  
            {  
                Debug.LogError ("Res.Load GUI/MessageBox error");  
                return null ;  
            }  
            GameObject go = NGUITools. AddChild(GameUIManager .mInstance. uiCamera.gameObject , prefab);  
            if (go == null)  
            {  
                Debug.LogError ("AddChild error");  
                return null ;  
            }  
            // 修改一下z值,为了适应界面上的材质表现  
            Vector3 pos = go.transform. localPosition;  
            pos.z += GameUIManager. UI_Z_OFFEST;  
            go.transform .localPosition = pos;  
            Instance = go .AddComponent< GameMessageBox>();  
        }  
        if (Instance != null)  
        {  
            Instance.Show (content, type, userData );  
        }  
        return Instance ;  
    }  
}  

测试界面,别忘了拖到摄像机上。
using UnityEngine ;  
using System .Collections;  
public class CutTest : MonoBehaviour {  
                 void OnGUI ()  
    {  
        if (GUI .Button( new Rect (10, 10, 100, 20), "OKMessage"))  
        {  
            GameMessageBox messageBox = GameMessageBox. ShowMessageBox("这是OK信息框" , MessageBox.Type .OK, null);  
            messageBox.CanCloseByFadeBGClicked = false;  
            messageBox.OkClick += OnOkClick;  
        }  
        if (GUI .Button( new Rect (10, 30, 100, 20), "OKCanelMessage"))  
        {  
            GameMessageBox messageBox = GameMessageBox. ShowMessageBox("这是OKCancel信息框" , MessageBox.Type .OKCancel, null);  
            messageBox.OkClick += OnOkClick;  
            messageBox.CancelClick += OnCancelClick;  
            messageBox.CanCloseByFadeBGClicked = true;  
        }  
        if (GUI .Button( new Rect (10, 50, 100, 20), "Custom1Message"))  
        {  
            GameMessageBox messageBox = GameMessageBox. ShowMessageBox("这是Custom1信息框" , MessageBox.Type .Custom1Btn, null);  
            messageBox.OkClick += OnCustome1Click;  
            messageBox.ContentPivot = UIWidget. Pivot.Center ;// 居中显示  
            messageBox.WidthOK = 132;  
            messageBox.CanCloseByFadeBGClicked = false;  
        }  
        if (GUI .Button( new Rect (10, 70, 100, 20), "Custom2Message"))  
        {  
            GameMessageBox messageBox = GameMessageBox. ShowMessageBox("这是Custome2信息框" , MessageBox.Type .Custom2Btn, null);  
            messageBox.OkClick += OnOkClick;  
            messageBox.CancelClick += OnCancelClick;  
            messageBox.CanCloseByFadeBGClicked = true;  
        }  
    }  
    private void OnCustome1Click (System. Object o )  
    {  
        Debug.Log ("Custom1Message");  
    }  
    private void OnOkClick (System. Object o )  
    {  
        Debug.Log ("OKMessage");  
    }  
    private void OnCancelClick (System. Object o )  
    {  
        Debug.Log ("CancelMessage");  
    }  
}  

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

0个评论