65 lines
2.0 KiB
C#
65 lines
2.0 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using UnityEngine.SceneManagement;
|
|
|
|
public class GlobalSafeArea : MonoBehaviour
|
|
{
|
|
private static GlobalSafeArea instance;
|
|
|
|
void Awake()
|
|
{
|
|
if (instance == null)
|
|
{
|
|
instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
SceneManager.sceneLoaded += OnSceneLoaded;
|
|
}
|
|
else
|
|
{
|
|
Destroy(gameObject);
|
|
}
|
|
}
|
|
|
|
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
|
|
{
|
|
ApplySafeAreaToScene();
|
|
}
|
|
|
|
void ApplySafeAreaToScene()
|
|
{
|
|
Canvas canvas = Object.FindFirstObjectByType<Canvas>();
|
|
if (canvas == null) return;
|
|
|
|
GameObject containerObj = GameObject.Find("Safe_Area_Container");
|
|
if (containerObj == null)
|
|
{
|
|
// Membuat container dan memasang komponen RectTransform serta SafeArea
|
|
containerObj = new GameObject("Safe_Area_Container", typeof(RectTransform));
|
|
|
|
// Tambahkan skrip SafeArea secara dinamis
|
|
containerObj.AddComponent<SafeArea>();
|
|
|
|
containerObj.transform.SetParent(canvas.transform, false);
|
|
|
|
RectTransform rect = containerObj.GetComponent<RectTransform>();
|
|
rect.anchorMin = Vector2.zero;
|
|
rect.anchorMax = Vector2.one;
|
|
rect.sizeDelta = Vector2.zero;
|
|
rect.anchoredPosition = Vector2.zero;
|
|
|
|
// Memindahkan semua UI ke dalam container agar aman dari notch/kamera HP
|
|
int childCount = canvas.transform.childCount;
|
|
for (int i = 0; i < childCount; i++)
|
|
{
|
|
if (canvas.transform.childCount > 0)
|
|
{
|
|
Transform child = canvas.transform.GetChild(0);
|
|
if (child.gameObject != containerObj)
|
|
{
|
|
child.SetParent(containerObj.transform, false);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |