To make your Canvas responsive in Unity, you primarily use the Canvas Scaler component attached to your root Canvas GameObject and set its UI Scale Mode to Scale With Screen Size.
Understanding the Canvas Scaler
The Canvas Scaler is a crucial component for controlling the overall scale and pixel density of UI elements within a Canvas. Without it, UI elements would maintain a fixed size regardless of the screen resolution, leading to interfaces that look too large or too small on different devices.
The Canvas Scaler component can be added to a root Canvas – which is a Game Object with a Canvas component on it, serving as the parent for all your UI elements. You'll find that this component is typically added by default when creating a new Canvas through the GameObject menu (UI -> Canvas).
Setting Up Responsive Scaling
The key to responsiveness lies in configuring the Canvas Scaler. Follow these steps:
- Select your root Canvas GameObject in the Hierarchy.
- In the Inspector window, locate the Canvas Scaler component.
- Find the UI Scale Mode property.
- Set the UI Scale Mode to Scale With Screen Size.
UI Scale Mode: Scale With Screen Size
When set to Scale With Screen Size, the Canvas Scaler adjusts the size of all UI elements within that Canvas based on the current screen resolution compared to a specified Reference Resolution.
- Reference Resolution: This is the screen size you design your UI for. Unity will scale UI elements up or down from this reference based on the actual screen size.
- Screen Match Mode: This setting (available when using Scale With Screen Size) determines how the scaling is applied when the screen's aspect ratio differs from the Reference Resolution. Common options include:
- Match Width Or Height: Scales based on matching either the width or the height, often controlled by a slider between 0 (match height) and 1 (match width).
- Expand: Ensures the Canvas always fits entirely within the screen by matching the dimension (width or height) that results in the smallest scale factor.
- Shrink: Ensures the Canvas never exceeds the screen boundaries by matching the dimension that results in the largest scale factor.
By setting the UI Scale Mode to Scale With Screen Size and properly configuring the Reference Resolution and Screen Match Mode, you ensure that your UI adapts gracefully to various screen sizes and resolutions, providing a consistent user experience.