Unity Ui无法正确缩放正交相机脚本

时间:2017-11-11 21:47:17

标签: c# unity3d 2d unity5 unityscript

我的ui元素在不同的屏幕分辨率下不会缩放我的2d安卓游戏,我很确定它与我附加到相机的脚本有关

 public class CameraResolutionFix : MonoBehaviour {
 public float orthographicSize = 5;
 public float aspect = 1.33333f;
 void Start()
 {
     Camera.main.projectionMatrix = Matrix4x4.Ortho(
         -orthographicSize * aspect, orthographicSize * aspect,
         -orthographicSize, orthographicSize,
         GetComponent<Camera>().nearClipPlane, GetComponent<Camera>().farClipPlane);
 }

}

1 个答案:

答案 0 :(得分:0)

您可能希望使用CanvasScaler,以下代码适用于我:

enter image description here

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

/// <summary>
/// Attach this script to objects that has a CanvasScaler component.
/// 
/// This makes sure the UI enlarges/shrinks when the device resolution changes.
///  
/// scaleFactor = 1.333f * Screen.height / 640;
/// Galuxy Notes 4: 2560X1440,  iphone 5s: (1136X640)
///         |                           |
///         v                           v
/// scaleFactor = 3                 scaleFactor = 1        
/// </summary>
public class DynamicCanvasScaler : MonoBehaviour {


    void Start () {
        AdjustDynamicCanvasScalar();

    }
    /// <summary>
    /// Canvas Scalar determins how large the UI elements are. On high resolution 
    /// deveices, this value should be larger, to make sure it is clearly visible
    /// and on low resolution devices, this should be kept smaller so that the UI
    /// menus are not so big.
    /// </summary>
    private void AdjustDynamicCanvasScalar()
    {
        var cs = gameObject.GetComponent<CanvasScaler>();
        if (cs == null)
            Debug.LogError("Cannot find the canvas scalar");
        else
        { //Galuxy Notes 4: 2560X1440, iphone 5s: (1136X640)  
            cs.scaleFactor = 1.333f * Screen.height / 640;
            Debug.Log("----------" + "Canvas Scalar = " + cs.scaleFactor + " ----------");
        }
    }
}