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

  • Unity UI Cookbook
  • Francesco Sapio
  • 523字
  • 2021-07-23 14:56:11

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

主站蜘蛛池模板: 康定县| 高密市| 辽源市| 舟曲县| 土默特右旗| 怀集县| 兰州市| 泸水县| 梅州市| 百色市| 沿河| 新绛县| 乌拉特中旗| 石棉县| 义马市| 阿勒泰市| 罗平县| 太白县| 苏尼特左旗| 济南市| 牡丹江市| 山阳县| 茂名市| 肇州县| 三穗县| 都匀市| 沙坪坝区| 宜州市| 凯里市| 美姑县| 克什克腾旗| 武义县| 修水县| 九江市| 奇台县| 安康市| 井冈山市| 汤阴县| 连南| 盖州市| 独山县|