Advertisement
Guest User

Unity MessageBox

a guest
Apr 5th, 2020
446
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using TMPro;
  4. using System;
  5. using System.Threading.Tasks;
  6.  
  7. public class MessageBox
  8. {
  9.     public enum buttons
  10.     {
  11.         ok,
  12.         cancel,
  13.  
  14.     }
  15.  
  16.     public readonly string Message;
  17.     public readonly string Title;
  18.     public readonly Action Callback;
  19.     public readonly GameObject UIMessageBox;
  20.  
  21.     private MessageBox(string message, string title, Action callback, buttons button)
  22.     {
  23.         Message = message;
  24.         Title = title;
  25.         UIMessageBox = DisplayBox(InGameMenu.Instance.messageBoxPrefab);
  26.         Callback = callback;
  27.         SetText(button);
  28.     }
  29.  
  30.     public static void Show(string errorMessage, string title)
  31.     {
  32.         new MessageBox(errorMessage, title, null, buttons.ok);
  33.     }
  34.  
  35.     public static void Show(string errorMessage, string title, Action callback)
  36.     {
  37.         new MessageBox(errorMessage, title, callback, buttons.ok);      
  38.     }
  39.  
  40.     public static void Show(string errorMessage, string title, Action callback, buttons button)
  41.     {
  42.         new MessageBox(errorMessage, title, callback, button);
  43.     }
  44.  
  45.  
  46.     private GameObject DisplayBox(GameObject prefab)
  47.     {
  48.  
  49.         return MonoBehaviour.Instantiate(prefab, InGameMenu.inGameMenuCanvas.transform);
  50.     }
  51.  
  52.     private void SetText(buttons buttonText)
  53.     {
  54.         UIMessageBox.transform.GetChild(0).Find("Header").GetChild(0).GetComponent<TMP_Text>().text = Title;
  55.         UIMessageBox.transform.GetChild(0).Find("Body").GetChild(0).GetComponent<TMP_Text>().text = Message;
  56.         UIMessageBox.transform.GetChild(0).Find("Button").GetChild(0).GetComponent<TMP_Text>().text = buttonText.ToString();
  57.         UIMessageBox.transform.GetChild(0).GetComponentInChildren<Button>().onClick.AddListener(delegate {
  58.             MonoBehaviour.Destroy(UIMessageBox);
  59.             if (Callback != null)
  60.             {
  61.                 Callback.Invoke();
  62.             }
  63.         });
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement