Image-1
Hello,
I am currently using AdMob banner ads in Unity, and what I want to do now is position the banner above the UI navigation bar, as shown in the image. However, the positioning seems to vary across different phone sizes.
private float ConvertPixelsToDP(float pixels)
{
return pixels / (Screen.dpi / 160);
}
private int ConvertPixelsToDeviceScale(float pixels)
{
return Mathf.RoundToInt(pixels / MobileAds.Utils.GetDeviceScale());
}
1-)
bannerView.SetPosition(0, ConvertPixelsToDP(ConvertPixelsToDeviceScale(Screen.height - offsetY - bannerView.GetHeightInPixels())));
This method works for some phones, but it doesn’t work correctly on all devices.
2-)
bannerView.SetPosition(0, ConvertPixelsToDP(ConvertPixelsToDeviceScale(Screen.height - offsetY - safeAreaTopPadding - bannerView.GetHeightInPixels())));
Here, I tried to account for the safe area by subtracting safeAreaTopPadding to handle devices with notches or different safe area sizes, but this still doesn’t work correctly.
3-) I also tried replacing the ConvertPixelsToDP() method with ConvertPixelsToDeviceScale() method as I’ve seen posts suggesting that Unity might be miscalculating for banner ads in certain cases.
Extra Information:
bannerView.SetPosition(0, 0);
When I set the y value to 0, the banner automatically uses the safe area for positioning.
Could anyone explain how bannerView.SetPosition() calculates the position? Or suggest a method to correctly place the AdMob banner above the UI navigation bar on different devices?
Any help would be greatly appreciated!
FurkanYildirim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Try the following method, it will surely help.
private void SetBannerPositionAboveNavigationBar()
{
Rect safeArea = Screen.safeArea;
float bannerHeightPx = 50f * Screen.dpi / 160f; // Assuming 50dp
float customY = safeArea.yMin + bannerHeightPx;
bannerView.SetPosition((int)(Screen.width / 2), (int)customY);
}