unity适配iPhoneX

1、思路

  主要思路就是,如果是iphoneX手机(手机型号信息可以参见SystemInfo属性),就将UI左右移动。

 

2、具体代码

using UnityEngine;
using System.Collections;

public class iPhoneXAdapter : MonoBehaviour
{
    public bool IsUseDebug = false;

    public iPhoneXAdapterSetting[] settings;

    private Vector3 initPosition;

#if UNITY_EDITOR || UNITY_IPHONE

    void Start()
    {
        initPosition = this.transform.localPosition;
    }

    void Update()
    {
        if (UDeviceGen.IsPhoneSafeRegions|| IsUseDebug)
        {
            if (settings != null && settings.Length > 0)
            {
                Vector3 tempPos = Vector3.zero;
                for (int i = 0; i < settings.Length; i++)
                {
                    if (settings[i].orientation == iPhoneXAdapterSetting.Orientation.All
                      || settings[i].orientation == iPhoneXAdapterSetting.Orientation.LandscapeLeft && Screen.orientation == ScreenOrientation.LandscapeLeft
                      || settings[i].orientation == iPhoneXAdapterSetting.Orientation.LandscapeRight && Screen.orientation == ScreenOrientation.LandscapeRight
                      || settings[i].orientation == iPhoneXAdapterSetting.Orientation.LandscapeLeft && Application.platform == RuntimePlatform.WindowsEditor
                      || IsUseDebug
                       )
                    {
                        switch (settings[i].axis)
                        {
                            case iPhoneXAdapterSetting.Axis.x:
                                tempPos += new Vector3(settings[i].offset, 0, 0);
                                break;
                            case iPhoneXAdapterSetting.Axis.y:
                                tempPos += new Vector3(0, settings[i].offset, 0);
                                break;
                        }
                    }
                }
                this.transform.localPosition = initPosition + tempPos;
            }
        }
    }

#endif
}

[System.Serializable]
public class iPhoneXAdapterSetting
{
    public enum Orientation { All, LandscapeLeft, LandscapeRight }
    public Orientation orientation = Orientation.All;
    public enum Axis { x, y }
    public Axis axis = Axis.x;
    public float offset;
}

3、代码使用示例

自动适配IPhoneX 右边屏

unity适配iPhoneX_第1张图片

你可能感兴趣的:(Unity3D)