using System.Collections; using TMPro; using UnityEngine; namespace XRMultiplayer { /// /// This class controls the display of the Player HUD Notification aka the Toast. /// public class PlayerHudNotification : MonoBehaviour { /// /// The singleton instance of this class. /// public static PlayerHudNotification Instance; [Header("Display Options")] [SerializeField] bool m_LockPitch = true; [SerializeField] bool m_LockRoll = true; /// /// The speed at which the toast follows the camera. /// [SerializeField] float m_FollowSpeed = 5.0f; /// /// The amount of time to display the toast. /// [SerializeField] float m_DisplayTime = 3.0f; /// /// The speed at which the toast fades in and out. /// [SerializeField] float m_ShowHideSpeed = 5.0f; [Header("Display References")] /// /// Text component to display the toast. /// [SerializeField] TMP_Text m_Text; /// /// The layout group transform that contains the toast. /// [SerializeField] Transform m_LayoutGroupTransform; /// /// The canvas group that contains the toast. /// [SerializeField] CanvasGroup m_CanvasGroup; /// /// The main camera. /// Camera m_Camera; /// /// The transform of this object. /// Transform m_Transform; /// private void Awake() { if (Instance != null) { Utils.Log("Instance is not null for PlayerHudNotification.", 2); enabled = false; return; } Instance = this; } /// private void Start() { m_Camera = Camera.main; m_Transform = transform; if (m_CanvasGroup == null) m_CanvasGroup = GetComponentInChildren(); m_CanvasGroup.alpha = 0.0f; m_LayoutGroupTransform.gameObject.SetActive(false); } [ContextMenu("Show Text Test")] void ShowTextTest() { ShowText("Test Text", m_DisplayTime); } /// /// Shows the toast with the given text. /// public void ShowText(string textToShow, float displayTime = 3.0f) { m_DisplayTime = displayTime; m_Text.text = textToShow; m_LayoutGroupTransform.gameObject.SetActive(true); StopAllCoroutines(); StartCoroutine(ShowRoutine()); } /// private void LateUpdate() { m_Transform.position = m_Camera.transform.position; Quaternion lookRot = Quaternion.LookRotation(m_Camera.transform.forward); Vector3 offset = lookRot.eulerAngles; if (m_LockPitch) offset.x = 0; if (m_LockRoll) offset.z = 0; lookRot = Quaternion.Euler(offset); m_Transform.rotation = Quaternion.Slerp(m_Transform.rotation, lookRot, Time.deltaTime * m_FollowSpeed); } /// /// Coroutine to show the toast. /// /// IEnumerator ShowRoutine() { while (m_CanvasGroup.alpha < 1.0f) { m_CanvasGroup.alpha += Time.deltaTime * m_ShowHideSpeed; yield return null; } StartCoroutine(DisplayRoutine()); } /// /// Coroutine to display the toast. /// /// IEnumerator DisplayRoutine() { yield return new WaitForSeconds(m_DisplayTime); StartCoroutine(HideTime()); } /// /// Coroutine to hide the toast. /// /// IEnumerator HideTime() { while (m_CanvasGroup.alpha > 0.0f) { m_CanvasGroup.alpha -= Time.deltaTime * m_ShowHideSpeed; yield return null; } m_LayoutGroupTransform.gameObject.SetActive(false); } } }