using UnityEngine; using System.Collections; public class NotifierBase : MonoBehaviour { public Canvas canvas; public GameObject notificationPrefab; protected GameObject notificationInstance; protected void ShowNotification(string text) { if (notificationPrefab == null || canvas == null) { return; } notificationInstance = Instantiate(notificationPrefab); notificationInstance.transform.SetParent(canvas.transform, false); notificationInstance.transform.localScale = Vector3.one; var notificationRect = notificationInstance.GetComponent(); var canvasRect = canvas.GetComponent(); var label = notificationInstance.GetComponent(); if (label != null) { label.text = text; } if (notificationRect != null && canvasRect != null) { Camera worldCamera = canvas.worldCamera != null ? canvas.worldCamera : Camera.main; Camera uiCamera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : worldCamera; if (worldCamera != null) { Vector2 screenPoint = worldCamera.WorldToScreenPoint(transform.position); if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPoint, uiCamera, out Vector2 localPoint)) { notificationRect.anchoredPosition = localPoint; } } } StartCoroutine(HideNotification()); } protected IEnumerator HideNotification() { yield return new WaitForSeconds(1.5f); if (notificationInstance != null) { Destroy(notificationInstance); } } }