官术网_书友最值得收藏!

Resizing the UI according to the screen size and resolution

One of the most difficult things to do in the older versions of Unity was scaling the UI (or GUI, the old Unity user interface system). In fact, the system was hard to learn, and most of the features had to be implemented by scripts, including scaling. However, in Unity 5, scaling the UI is much easier with the Canvas Scaler (Script) component. This component will take care of the scale of all UI elements that are contained in Canvas.

How to do it...

  1. If we check the previous recipe, we can see in the Hierarchy panel that Canvas is already present in our scene. This is because whenever we create a UI element and Canvas is not present in the scene, Unity will create it for us. Of course, we can also create it on our own, and this can be done by right-clicking on the Hierarchy panel and then navigating to UI | Canvas.
  2. Now that we have created Canvas, we can select it. In the Inspector, we can see all its properties and parameters, including all the components attached to it. By default, when a Canvas is created, the Canvas Scaler (Script) component is attached on it. Since this component can be removed, it may happen that it is not present anymore. In such cases, we can add it again by clicking inside the Inspector window on Add Component and then going to Layout | Canvas Scaler.
  3. Next, we have to change the Ui Scale Mode property to Scale With Screen Size and ensure that Screen Match Mode is set to Match Width Or Height. Furthermore, we can adjust the Match variable; for example, we can move the slider to the middle by changing the value to 0.5. We should now see this:
  4. As a result, every UI element inside Canvas will be scaled according to our project's screen resolution, and they will all adapt to the device on which the game is running.

How it works...

In the Unity UI system, Canvas is a special game object. This is because all the UI elements must be contained inside it. In fact, elements that are not in it will not be rendered. By default, Canvas comes with three components attached to it. One of these three is Canvas Scaler (Script). This component controls how all the UI elements that are contained in that specific Canvas will be scaled. By tweaking some of its properties, it is possible to achieve a scale setting that best suits our needs. In particular, we have set the Match slider, which allows us to proportionally crop the width and height of the view in order to adapt it to the resolution of the platform on which the game is running.

See also

主站蜘蛛池模板: 桓台县| 叶城县| 靖远县| 红原县| 若羌县| 泸州市| 温州市| 胶南市| 武隆县| 木兰县| 阿拉善左旗| 绥阳县| 馆陶县| 江源县| 赫章县| 德钦县| 洛宁县| 鹰潭市| 镇巴县| 鹰潭市| 巴马| 潼南县| 卓尼县| 九江市| 瑞安市| 林甸县| 萍乡市| 昆明市| 襄樊市| 扎鲁特旗| 通山县| 东宁县| 乌审旗| 通城县| 昭通市| 凤台县| 连州市| 莫力| 海阳市| 开原市| 钟祥市|