TLDR After initial message.
I'm building a dynamic inventory system where text items are placed in rows, creating a new row when items don't fit. I'm facing a strange issue with viewport width calculations.
The Problem
I need to determine the available width to decide when to create a new row. However, the viewport.rect.width values I'm getting are drastically different between resolutions:
In 1440x2960: viewport.rect.width = 1481.03
In 2960x1440: viewport.rect.width = 6125.474
This is causing layout issues where:
Items overflow in 1440x2960
Items don't fill the space efficiently in 2960x1440
What I've Tried
Using TextMeshPro's preferredWidth:
float itemWidth = itemNameTMP.preferredWidth;
Using LayoutElement's preferredWidth:
float itemWidth = item.GetComponent<LayoutElement>().preferredWidth;
Using Reference Resolution:
float usableWidth = canvasScaler.referenceResolution.x;
Using Viewport Width with Safety Margin:
float usableWidth = viewport.rect.width * 0.95f;
Using Different Safety Margins Based on Resolution:
float safetyMargin = (Screen.width > Screen.height) ? 1.0f : 0.75f; float usableWidth = viewport.rect.width * safetyMargin;
None of these approaches work consistently across both resolutions.
My Canvas Setup
Canvas Scaler UI Scale Mode: ScaleWithScreenSize
Reference Resolution: (1440, 2960)
Screen Match Mode: MatchWidthOrHeight
Match value: 1 (match height)
The Question
Why is viewport.rect.width so much larger (6125) in 2960x1440 compared to 1440x2960 (1481)?
What's the proper way to calculate available width for UI elements that works consistently across all resolutions?