Tutorials , Articles and Hope!
Tutorials , Articles and Hope!
MobileSafeArea

How to create a safe area panel.

MobileSafeArea

Nowadays with new devices gaining even more intricate displays and bullet cameras making their appearance sometimes we need a way to create UI content inside the screen area without being obstructed by the camera or notches of the device. In spite of this we will be creating a safe area panel! This is a simple script that detects that area and adjusts all content inside the container.

Project Setup.

Lets start by creating a new project , if you already have a project skip to the next step , and importing the DeviceSimulator package from the Unity Registry. The Device simulator allows us to view our games as they would appear in the device thus allowing us to cut down on production time from having to build the project in every update! That being said , we should though build the game to test out on the device on various checkpoints of development!

newProject
SetupDeviceSimulator
CanvasCreate

Creating the canvas.

We navigate to either the + icon in the hierarchy or by right clicking and selecting UI -> Canvas. That creates an empty canvas for all out UI elements. On that canvas we attach the following script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SafeAreaDetection : MonoBehaviour
{
    public delegate void SafeAreaChanged(Rect safeArea);
    public static event SafeAreaChanged OnSafeAreaChanged;

    private Rect _safeArea;

    private void Awake()
    {
        _safeArea = Screen.safeArea;
    }

    void Update()
    {
        if (_safeArea != Screen.safeArea)
        {
            _safeArea = Screen.safeArea;
            OnSafeAreaChanged?.Invoke(_safeArea);
        }
    }
}

Now in order to explain it we first have to understand Delegates and Events.

Explaining Delegates && Events.

A Delegate is a reference pointer to a method. It allows us to treat a method as a variable and pass method as a variable for a callback. On call the delegate notifies all methods that reference it, think of it as a subscription service , were many users subscribe to an event and they all get the result back at the same time.

On the other hand Events, are a type of special delegate which are used when you want to notify other classes when something happens like on game over / game start or through other conditions!

Adding the safe area panel script.

At this point we should have:

  • A blank project.
  • A blank Canvas.
  • The Device Simulator Installed.
  • The panel detection script attached to out canvas.

It is now time to create the script that handles the panel repositioning!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SafeAreaPanel : MonoBehaviour
{
    private RectTransform _rectTransform;

    private void Awake()
    {
        _rectTransform = GetComponent<RectTransform>();
        RefreshPanel(Screen.safeArea);
    }

    private void OnEnable()
    {
        SafeAreaDetection.OnSafeAreaChanged += RefreshPanel;
    }

    private void OnDisable()
    {
        SafeAreaDetection.OnSafeAreaChanged -= RefreshPanel;
    }

    private void RefreshPanel(Rect safeArea)
    {
        Vector2 anchorMin = safeArea.position;
        Vector2 anchorMax = safeArea.position + safeArea.size;

        anchorMin.x /= Screen.width;
        anchorMin.y /= Screen.height;
        anchorMax.x /= Screen.width;
        anchorMax.y /= Screen.height;

        _rectTransform.anchorMin = anchorMin;
        _rectTransform.anchorMax = anchorMax;
    }
}

Explaining the safe area panel script

To further explain the second script , we start by referencing the RectTransform of the panel , which we will create in a bit! , That RectTrasnform is essentially our panel that will get positioned inside the devices safe are panel. I trust that you are familiar with functions in Unity , but in case you are not i will go through them as quickly and easy as possible.

Before that you should take a look at this part from Unity’s Documentation!

  • Void Awake runs first in our script.
  • Void OnEnable runs second.
  • Void OnDisable runs when we kill the app!

With this in mind , in the awake function we reference that component so Unity would know what element to check! Next in line is the OnEnable function were we use our previously create event to call upon the RefreshPanel function. That particular panel takes into account the anchors of our RectTransform and sets them based on the screen width and height. So in sum , on awake we check the transform, we run the function to adjust the panel and once we kill / close the game everything reverts back to the initial state.
Next in line is creating some UI elements for testing as well as a panel that holds them!

Creating the safe area panel.

In addition to our canvas we now need to add a panel in order to hold our elements. For this particular tutorial i will be making a few text elements positioned on the edges of the canvas.
On the subject of creating said panel we navigate to our Canvas element, right click it and select UI -> Create panel which in turn will create an empty panel with an overlay.

safe area panel

Adding the text elements and testing.

Altogether so far we should have our Canvas , our safe area panel and some elements positioned on the edges of the canvas. To clarify our text elemets are achored to the edges through their rect transform! To do that we select our text element and by going into the Rect transform component and clicking on that box with the lines!

pivotpoints

To sum up our project!

At this point we should have a fully working safe area panel prototype! And to illustrate our hard work we can press the play button and see the results!

safeareaOff
safeAreaOn

Finally you can go ahead and disable the safe area representation by clicking on the corresponding button inside our game window! And there we have it! a working safe area detection which works on all mobile devices!

You can also get this project directly from my GitHub!
Press here to get it!

Leave a comment