Closed Fenikkel closed 3 months ago
Ok, I find the solution. It only works on Unity 6 and forwards:
`using System; using UnityEngine; using UnityEngine.UIElements;
/* Disclaimer: Minimum version compatible -> Unity 6
TODO: Make non-editable the Spacing property in the UI Builder
*/
[UxmlElement("SafeArea")] // Cannot contain special characters public partial class SafeAreaManager : VisualElement { [UxmlAttribute] public SafeAreaSpacing SafeAreaType { get; set; }
public enum SafeAreaSpacing
{
Margin, // Makes visible the screen behind or the camera background
Padding // Makes visible the background of the visual element (SafeArea)
}
public SafeAreaManager() // Constructors are called on Awake()
{
style.flexGrow = 1;
style.flexShrink = 1;
RegisterCallback<GeometryChangedEvent>(LayoutChanged);
}
private void LayoutChanged(GeometryChangedEvent geomentryChangedEvent)
{
try
{
(Vector2 leftTop, Vector2 rightBottom) = SafeArea();
switch (SafeAreaType)
{
case SafeAreaSpacing.Margin:
style.marginLeft = leftTop.x;
style.marginTop = leftTop.y;
style.marginRight = rightBottom.x;
style.marginBottom = rightBottom.y;
break;
case SafeAreaSpacing.Padding:
style.paddingLeft = leftTop.x;
style.paddingTop = leftTop.y;
style.paddingRight = rightBottom.x;
style.paddingBottom = rightBottom.y;
break;
default:
Debug.LogWarning("Not implemented");
break;
}
}
catch (InvalidCastException){} // Throwed each time we safe the in the UI Builder
}
private (Vector2, Vector2) SafeArea()
{
Rect safeArea = Screen.safeArea;
Vector2 leftTop = RuntimePanelUtils.ScreenToPanel(this.panel,
new Vector2(safeArea.xMin, Screen.height - safeArea.yMax));
Vector2 rightBottom = RuntimePanelUtils.ScreenToPanel(this.panel,
new Vector2(Screen.width - safeArea.xMax, safeArea.yMin));
return (leftTop, rightBottom);
}
}`
Hi, and thanks for the nice code.
The issue is that at least in Unity 6 (preview), it shows a warning about UxmlTraits being obsolete.
I've tried to update it, but I can't. Do you have any idea how to fix this bug in the future?
Thanks.