ArkanoidTG/Assets/Scripts/UIManager.cs

105 lines
3.4 KiB
C#
Raw Permalink Normal View History

2024-11-25 23:14:57 +03:00
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class UIManager : MonoBehaviour
{
public static UIManager Instance { get; private set; }
private TextMeshProUGUI statsText;
private GameManager gameManager;
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
return;
}
gameManager = FindObjectOfType<GameManager>();
if (gameManager == null)
{
Debug.LogError("GameManager not found!");
return;
}
CreateUI();
}
void CreateUI()
{
// Проверяем наличие шрифта для WebGL
if (TMP_Settings.defaultFontAsset == null)
{
Debug.LogError("Default TMP font asset is missing! UI text may not be visible in WebGL build.");
return;
}
// Create Canvas
GameObject canvasObj = new GameObject("StatsCanvas");
canvasObj.transform.SetParent(transform);
Canvas canvas = canvasObj.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvasObj.AddComponent<CanvasScaler>();
canvasObj.AddComponent<GraphicRaycaster>();
// Create Text object
GameObject textObj = new GameObject("StatsText");
textObj.transform.SetParent(canvasObj.transform, false);
statsText = textObj.AddComponent<TextMeshProUGUI>();
// Configure text component
statsText.font = TMP_Settings.defaultFontAsset;
statsText.fontSize = 24f;
statsText.fontStyle = FontStyles.Bold;
statsText.enableWordWrapping = true;
statsText.overflowMode = TextOverflowModes.Overflow;
statsText.horizontalMapping = TextureMappingOptions.Line;
statsText.verticalMapping = TextureMappingOptions.Line;
// Добавляем обводку для лучшей видимости
statsText.outlineWidth = 0.2f;
statsText.outlineColor = Color.black;
statsText.color = Color.white;
// Position text in top-left corner
RectTransform rectTransform = textObj.GetComponent<RectTransform>();
rectTransform.anchorMin = new Vector2(0, 1);
rectTransform.anchorMax = new Vector2(0, 1);
rectTransform.pivot = new Vector2(0, 1);
rectTransform.anchoredPosition = new Vector2(10, -10);
rectTransform.sizeDelta = new Vector2(200, 100);
}
void Update()
{
if (gameManager != null)
{
UpdateStats(
gameManager.DestroyedBricks,
gameManager.TotalBricks,
gameManager.UsedLives,
gameManager.InitialLives
);
}
}
private void UpdateStats(int destroyedBricks, int totalBricks, int usedLives, int totalLives)
{
if (statsText != null)
{
// Загружаем номер сборки из ресурсов
TextAsset buildVersionAsset = Resources.Load<TextAsset>("buildVersion");
string buildVersion = buildVersionAsset != null ? buildVersionAsset.text : "1";
// Обновляем текст с номером сборки
statsText.text = $"Bricks: {destroyedBricks}/{totalBricks}\nLives Used: {usedLives}/{totalLives}\nBuild: {buildVersion}";
}
}
}