C# 统一:用户界面元素脱离相机。。(所有图像和内部代码)

C# 统一:用户界面元素脱离相机。。(所有图像和内部代码),c#,android,unity3d,C#,Android,Unity3d,我终于完成了我的第一个简单2D游戏。。但现在我撞到了墙。。我正在尝试调整多屏幕游戏(Android)。我在1080 x 1920分辨率上构建了游戏。。现在,为了使它适应不同的屏幕分辨率,我使用了这段代码,它对我很有用 public class ControllingCameraAspectScript : MonoBehaviour { // Use this for initialization void Start() { // set the de

我终于完成了我的第一个简单2D游戏。。但现在我撞到了墙。。我正在尝试调整多屏幕游戏(Android)。我在1080 x 1920分辨率上构建了游戏。。现在,为了使它适应不同的屏幕分辨率,我使用了这段代码,它对我很有用

public class ControllingCameraAspectScript : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        // set the desired aspect ratio (the values in this example are
        // hard-coded for 16:9, but you could make them into public
        // variables instead so you can set them at design time)
        float targetaspect = 1080.0f / 1920.0f;

        // determine the game window's current aspect ratio
        float windowaspect = (float)Screen.width / (float)Screen.height;

        // current viewport height should be scaled by this amount
        float scaleheight = windowaspect / targetaspect;

        // obtain camera component so we can modify its viewport
        Camera camera = GetComponent<Camera>();

        // if scaled height is less than current height, add letterbox
        if (scaleheight < 1.0f)
        {
            Rect rect = camera.rect;

            rect.width = 1.0f;
            rect.height = scaleheight;
            rect.x = 0;
            rect.y = (1.0f - scaleheight) / 2.0f;

            camera.rect = rect;
        }
        else // add pillarbox
        {
            float scalewidth = 1.0f / scaleheight;

            Rect rect = camera.rect;

            rect.width = scalewidth;
            rect.height = 1.0f;
            rect.x = (1.0f - scalewidth) / 2.0f;
            rect.y = 0;

            camera.rect = rect;
        }
    }

}
公共类控制CameraAspectScript:MonoBehavior
{
//用于初始化
void Start()
{
//设置所需的纵横比(本例中的值为
//16:9的硬编码,但你可以公开
//变量,以便您可以在设计时设置它们)
浮动目标光谱=1080.0f/1920.0f;
//确定游戏窗口的当前纵横比
float windowaspect=(float)Screen.width/(float)Screen.height;
//当前视口高度应按此量缩放
float-scaleheight=窗口纵横比/targetspect;
//获取摄影机组件,以便我们可以修改其视口
摄像头=GetComponent();
//如果缩放高度小于当前高度,请添加信箱
如果(刻度高度<1.0f)
{
Rect Rect=camera.Rect;
矩形宽度=1.0f;
rect.height=刻度高度;
rect.x=0;
矩形y=(1.0f-刻度高度)/2.0f;
camera.rect=rect;
}
否则//添加柱垫
{
浮动刻度宽度=1.0f/刻度高度;
Rect Rect=camera.Rect;
rect.width=缩放宽度;
垂直高度=1.0f;
rect.x=(1.0f-标度宽度)/2.0f;
矩形y=0;
camera.rect=rect;
}
}
}
谢天谢地,游戏中的物体就位了。。但用户界面元素不在摄像机内。。请看图片


我已经在使用Canvas Scaler和带有UI元素的锚。

Canvas Scaler组件中,您可以将其UI缩放模式设置为按屏幕大小缩放


我找到的解决问题的简单方法是遵循本教程


发布画布缩放器设置的屏幕截图。如果用户界面元素不在相机外,请点击。这里的问题是二维图形无法填充屏幕宽度。(正如您在图片中看到的,有两个黑色边框)所以您需要编写一个基于屏幕宽度和高度的代码,保持纵横比。这是画布设置@SteeBono你能帮我吗?如果我可以编辑我的相机代码?@HaniDarker您可以尝试的第一件事是设置:-屏幕匹配模式:宽度-匹配:0通过这些更改,游戏的宽度始终适合宽度。之后,您只需要调整高度,例如增加背景的高度