1.调用和定制消息框内容脚本
using UnityEngine;
class MessageBox
{
static Object cacheObject = null;
public static UIMessageBox Show(string message, string title = "", MessageBoxType type = MessageBoxType.Information, string btnOK = "", string btnCancel = "")
{
if (cacheObject == null)
{
cacheObject = Resloader.Load<Object>("UI/UIMessageBox");
}
GameObject go = (GameObject)GameObject.Instantiate(cacheObject);
UIMessageBox msgbox = go.GetComponent<UIMessageBox>();
msgbox.Init(title, message, type, btnOK, btnCancel);
return msgbox;
}
}
public enum MessageBoxType
{
/// <summary>
/// Information Dialog with OK button
/// </summary>
Information = 1,
/// <summary>
/// Confirm Dialog whit OK and Cancel buttons
/// </summary>
Confirm = 2,
/// <summary>
/// Error Dialog with OK buttons
/// </summary>
Error = 3
}
2.绑定到预制体消息框脚本
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class UIMessageBox : MonoBehaviour
{
public Text title;
public Text message;
public Image[] icons;
public Button buttonYes;
public Button buttonNo;
public Button buttonClose;
public Text buttonYesTitle;
public Text buttonNoTitle;
public UnityAction OnYes;
public UnityAction OnNo;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void Init(string title, string message, MessageBoxType type = MessageBoxType.Information, string btnOK = "", string btnCancel = "")
{
if (!string.IsNullOrEmpty(title)) this.title.text = title;
this.message.text = message;
this.icons[0].enabled = type == MessageBoxType.Information;
this.icons[1].enabled = type == MessageBoxType.Confirm;
this.icons[2].enabled = type == MessageBoxType.Error;
if (!string.IsNullOrEmpty(btnOK)) this.buttonYesTitle.text = btnOK;
if (!string.IsNullOrEmpty(btnCancel)) this.buttonNoTitle.text = btnCancel;
this.buttonYes.onClick.AddListener(OnClickYes);
this.buttonNo.onClick.AddListener(OnClickNo);
this.buttonNo.gameObject.SetActive(type == MessageBoxType.Confirm);
}
void OnClickYes()
{
Destroy(this.gameObject);
if (this.OnYes != null)
this.OnYes();
}
void OnClickNo()
{
Destroy(this.gameObject);
if (this.OnNo != null)
this.OnNo();
}
}
调试代码:
MessageBox.Show("两次输入的密码不一致");