using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; namespace UI { /// /// Automatically sets up a full-screen Canvas and creates a Window on scene start. /// Attach this component to any GameObject in the scene. /// public class UIInitializer : MonoBehaviour { [Header("Window Settings")] [SerializeField] private string windowTitle = "Window"; [SerializeField] private Vector2 windowSize = new Vector2(600, 400); [SerializeField] private Vector2 windowPosition = Vector2.zero; private void Start() { SetupCanvas(); SetupEventSystem(); CreateWindow(); } /// /// Creates a full-screen Canvas if one doesn't exist /// private void SetupCanvas() { Canvas existingCanvas = FindObjectOfType(); if (existingCanvas != null) { Debug.Log("Canvas already exists, using existing canvas."); return; } // Create Canvas GameObject GameObject canvasObj = new GameObject("Canvas"); Canvas canvas = canvasObj.AddComponent(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.sortingOrder = 0; // Add CanvasScaler CanvasScaler scaler = canvasObj.AddComponent(); scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; scaler.referenceResolution = new Vector2(1920, 1080); scaler.matchWidthOrHeight = 0.5f; // Add GraphicRaycaster canvasObj.AddComponent(); Debug.Log("Canvas created successfully."); } /// /// Sets up EventSystem with InputSystemUIInputModule for new Input System /// private void SetupEventSystem() { EventSystem existingEventSystem = FindObjectOfType(); if (existingEventSystem != null) { Debug.Log("EventSystem already exists, checking InputSystemUIInputModule..."); // Check if InputSystemUIInputModule exists if (existingEventSystem.GetComponent() == null) { // Remove old StandaloneInputModule if it exists var oldModule = existingEventSystem.GetComponent(); if (oldModule != null) { DestroyImmediate(oldModule); } // Add InputSystemUIInputModule existingEventSystem.gameObject.AddComponent(); Debug.Log("Added InputSystemUIInputModule to existing EventSystem."); } return; } // Create EventSystem GameObject GameObject eventSystemObj = new GameObject("EventSystem"); EventSystem eventSystem = eventSystemObj.AddComponent(); // Add InputSystemUIInputModule for new Input System eventSystemObj.AddComponent(); Debug.Log("EventSystem with InputSystemUIInputModule created successfully."); } /// /// Creates and positions a Window /// private void CreateWindow() { Canvas canvas = FindObjectOfType(); if (canvas == null) { Debug.LogError("Cannot create window: Canvas not found!"); return; } // Create Window GameObject GameObject windowObj = new GameObject("Window"); windowObj.transform.SetParent(canvas.transform, false); // Add Window component Window window = windowObj.AddComponent(); window.SetTitle(windowTitle); // Set window position RectTransform windowRect = windowObj.GetComponent(); if (windowRect != null) { windowRect.anchoredPosition = windowPosition; } Debug.Log($"Window '{windowTitle}' created successfully."); } } }