You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#解决手机凸起摄像头遮挡UI按钮方案咨询

Unity中解决凸起摄像头遮挡UI按钮的C#方案

直接用Unity自带的Screen.safeArea属性就能搞定,这是系统提供的屏幕安全区域数据,能精准避开摄像头、刘海这类遮挡区域。下面给两个实用的实现方案:

方案一:全局适配整个UI画布

给你的Canvas根节点挂这个脚本,自动把整个UI布局限制在安全区域内,一劳永逸:

using UnityEngine;

[RequireComponent(typeof(RectTransform))]
public class SafeAreaCanvasAdapter : MonoBehaviour
{
    private RectTransform _canvasRect;

    void Start()
    {
        _canvasRect = GetComponent<RectTransform>();
        ApplySafeArea();
        // 监听屏幕旋转/尺寸变化,实时更新
        Screen.onOrientationChange += ApplySafeArea;
    }

    void ApplySafeArea()
    {
        Rect safeArea = Screen.safeArea;
        // 把安全区域坐标转换为Canvas的局部坐标
        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;

        _canvasRect.anchorMin = anchorMin;
        _canvasRect.anchorMax = anchorMax;
    }

    void OnDestroy()
    {
        Screen.onOrientationChange -= ApplySafeArea;
    }
}

方案二:单独适配特定按钮

如果不想全局调整,只想修复被遮挡的单个按钮,给目标按钮挂这个脚本,让它自动避开安全区域边缘:

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Button))]
public class SafeAreaButtonAdapter : MonoBehaviour
{
    private RectTransform _buttonRect;
    // 可以手动设置额外的安全间距,防止贴太近
    public float extraMargin = 10f;

    void Start()
    {
        _buttonRect = GetComponent<RectTransform>();
        AdjustButtonPosition();
        Screen.onOrientationChange += AdjustButtonPosition;
    }

    void AdjustButtonPosition()
    {
        Rect safeArea = Screen.safeArea;
        // 获取按钮在屏幕上的世界坐标
        Vector3[] buttonCorners = new Vector3[4];
        _buttonRect.GetWorldCorners(buttonCorners);
        
        // 检查按钮是否超出安全区域(以左上角摄像头区域为例,可根据需求调整)
        if (buttonCorners[1].x < safeArea.xMin)
        {
            float offset = safeArea.xMin - buttonCorners[1].x + extraMargin;
            _buttonRect.anchoredPosition += new Vector2(offset, 0);
        }
        // 其他方向的遮挡检查可以同理添加
    }

    void OnDestroy()
    {
        Screen.onOrientationChange -= AdjustButtonPosition;
    }
}

测试技巧

在Unity的Game视图顶部,选择带刘海/凸起摄像头的预设机型(比如iPhone 14 Pro),切换横竖屏看适配效果,不需要真机就能提前验证。

内容的提问来源于stack exchange,提问作者Orela Studio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 14:42:13