유니티(Unity)
Unity 알림텍스트
KimSJ
2024. 4. 1. 12:04
using UnityEngine;
using UnityEngine.UI;
public class Notification : MonoBehaviour
{
static GameObject notifyText, canvasObject, panelObject;
public static Notification instance = null;
public static Notification Instance
{
get
{
if(instance == null)
{
CreateText();
CreateCanvas();
CreatePanel();
instance = canvasObject.AddComponent<Notification>();
}
return instance;
}
}
static void CreateText()
{
notifyText = new GameObject("NotificationCanvas");
notifyText.AddComponent<Disappearance>();
notifyText.AddComponent<TMPro.TextMeshProUGUI>().fontSize = 50;
notifyText.GetComponent<RectTransform>().sizeDelta = new Vector2(1000f, 60f);
}
static void CreateCanvas()
{
canvasObject = new GameObject("NotificationCanvas");
Canvas canvas = canvasObject.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvasObject.AddComponent<GraphicRaycaster>();
CanvasScaler canvasScaler = canvasObject.AddComponent<CanvasScaler>();
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvasScaler.referenceResolution = new Vector2(1920, 1080);
DontDestroyOnLoad(canvasObject);
}
static void CreatePanel()
{
if (canvasObject == null) return;
panelObject = new GameObject("Panel");
RectTransform panelRectTransform = panelObject.AddComponent<RectTransform>();
panelRectTransform.SetParent(canvasObject.transform, false);
panelRectTransform.sizeDelta = new Vector2(1000f, 0f);
panelRectTransform.position = new Vector3(Screen.width / 2, Screen.height / 5 * 4, 0);
UnityEngine.UI.Image panelImage = panelObject.AddComponent<UnityEngine.UI.Image>();
panelImage.color = new Color(0, 0, 0, 0);
VerticalLayoutGroup verticalLayoutGroup = panelObject.AddComponent<VerticalLayoutGroup>();
verticalLayoutGroup.spacing = 5f;
ContentSizeFitter contentSizeFitter = panelObject.AddComponent<ContentSizeFitter>();
contentSizeFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
}
public string notification
{
set
{
if (value != "" && value != null)
{
Notify(value);
}
}
}
void Notify(string notice)
{
Instantiate(notifyText, panelObject.transform).GetComponent<TMPro.TextMeshProUGUI>().text = notice;
}
}
using UnityEngine;
public class Disappearance : MonoBehaviour
{
void Start()
{
Invoke("Disappear", 10f);
}
void Disappear()
{
Destroy(gameObject);
}
}
사용 예시
Notification.Instance.notification = "All files have already been downloaded.";