UGUI—对话框(DialogBox)

作者:追风剑情 发布于:2021-9-27 15:57 分类:Unity3d

示例:对话框

工程截图

111.png

代码

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 对话框UI
/// </summary>
public class DialogBox : GameEventBehaviour
{
    public static DialogBox Instance { get; private set; }

    [SerializeField]
    private GameObject mask;
    [SerializeField]
    private GameObject okButton;
    [SerializeField]
    private GameObject cancelButton;
    [SerializeField]
    private Text m_Text;
    [SerializeField]
    private Text m_TextOk;
    private Action okCallback = null;
    private float freezeClickTime = -1f;

    public enum ButtonLayout
    {
        None,       //不显示操作按钮
        OK,         //只显示确认按钮
        OK_Cancel   //同时显示确认和取消按钮
    }

    protected override void OnAwake()
    {
        Instance = this;
    }

    protected override void OnUpdate()
    {
        if (freezeClickTime <= 0)
            return;

        freezeClickTime -= Time.deltaTime;
        if (freezeClickTime <= 0)
        {
            m_TextOk.text = Config.LAN_BUTTON_SURE;
        }
        else
        {
            int cd = Mathf.CeilToInt(freezeClickTime);
            m_TextOk.text = string.Format("{0}({1})", Config.LAN_BUTTON_SURE, cd);
        }
    }

    public void Close()
    {
        mask.SetActive(false);
    }

    public void OnClickOK()
    {
        if (freezeClickTime > 0)
            return;

        Close();
        if (this.okCallback != null)
            this.okCallback();
        this.okCallback = null;
    }

    public void OnClickCancel()
    {
        Close();
        this.okCallback = null;
        freezeClickTime = -1;
    }

    public void Show(string text, ButtonLayout layout=ButtonLayout.OK, Action okCallback=null, float freezeClickTime = -1)
    {
        m_Text.text = text + "\n";
        m_TextOk.text = Config.LAN_BUTTON_SURE;
        mask.SetActive(true);
        okButton.SetActive(layout == ButtonLayout.OK || layout == ButtonLayout.OK_Cancel);
        cancelButton.SetActive(layout == ButtonLayout.OK_Cancel);

        RectTransform okRectTransform = okButton.GetComponent<RectTransform>();
        if (layout == ButtonLayout.OK_Cancel)
            SetAnchoredPositionX(okRectTransform, -121f);
        else
            SetAnchoredPositionX(okRectTransform, 0f);

        this.okCallback = okCallback;
        this.freezeClickTime = freezeClickTime;
    }

    private void SetAnchoredPositionX(RectTransform rectTransform, float x)
    {
        Vector2 anchoredPosition = rectTransform.anchoredPosition;
        anchoredPosition.x = x;
        rectTransform.anchoredPosition = anchoredPosition;
    }
}

效果

2222.png

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号