why

Screen.SetResolution(width, height, true); Screen.SetResolution(width, height, true); However, if the resolution is manually set and the Screen Width is obtained through [Screen Width], it is the value after manual setting. As a result, in the split screen mode of an Android phone, the screen width and height cannot be obtained after adjusting the size, causing the screen to stretch.

To solve

Since Unity has no interface to get the changed form size, start with the Java layer. The onConfigurationChanged event will be triggered when the phone state changes, such as vertical and horizontal screen changes, screen size changes, pop-up keyboard and system Settings changes, etc. Then we will inform the C# layer by ourselves, and calculate the density independent pixel size with DPI into pixels. Finally, the resolution is reset based on the width and height.

Java layer

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        UnityPlayer.UnitySendMessage("SdkManager"."OnScreenDpChanged", newConfig.screenWidthDp +"x" + newConfig.screenHeightDp);
    }
Copy the code

C # layer

     public void OnScreenDpChanged(string screenDpStr)
     {
         LogModule.LogDebug(LogScenario.DevicesInfo, "OnScreenDpChanged {0}", screenDpStr);
         if (!string.IsNullOrEmpty(screenDpStr))
         {
             CheckScreenDpChanged(screenDpStr, false); }}/// <summary>
     ///Check for changes in physical resolution
     /// </summary>
     public void CheckScreenDpChanged(string screenDpStr, bool isPixel)
     {
         if (m_ScreenDp == screenDpStr)
         {
             return;
         }

         try
         {
             m_ScreenDp = screenDpStr;
             string[] res = screenDpStr.Split('x');
             int width = int.Parse(res[0]);
             int height = int.Parse(res[1]);

             // If it is a pixel, there is no need to calculate with DPI
             if(! isPixel) {float dpi = Screen.dpi;
                 width = Mathf.FloorToInt(dpi / 160 * width);
                 height = Mathf.FloorToInt(dpi / 160 * height);
             }

             if(m_Width ! = width || m_Height ! = height) { m_Width = width; m_Height = height; SetResolution(m_Config); } } catch (Exception) {// ignored}}Copy the code