Reputation: 23
I am trying to work out something for CellSize in Unity. This is for the GridLayoutGroup component. I found something that when done with a calculator works perfectly fine: Screen.Width/1280 , Screen.Height/720. Since I am using 720p as the base resolution and everything looks fine on there I use it as a base. 100x100 looks great for cell size on 720p.
For example their resolution is 1280:1024 It should come out (100, 142) However it always comes out (1.0, 1.0). If the resolution is tiny... such as 320x200 it comes out (0.0, 0.0).
Here is my code:
SlotPanel.GetComponent<GridLayoutGroup>().cellSize = new Vector2((Cam.pixelWidth / 1280) * 100, (Cam.pixelHeight / 720) * 100);
Cam is the Camera that the player uses. Another code that I tried was:
SlotPanel.GetComponenet<GridLayoutGroup>().cellSize = new Vector2((Screen.Width / 1280) * 100, (Screen.Height / 720) * 100);
Both result in the same issue. At this point I am at a loss of words for how annoyed I am. I don't understand why the math is right, but it does not work right.
Upvotes: 1
Views: 126
Reputation: 234685
Cam.pixelWidth / 1280
&c. is evaluated in integer arithmetic; any remainder is discarded.
Rewrite to 100.0 * Cam.pixelWidth / 1280
to ensure the evaluation takes place in floating point (due to promotion of the two integral arguments). There are other ways, but I find this one to be clearest since changing the first coefficient tells a reader of your code from the get-go what you want to do.
(If you require the type of the expression to be a single precision floating point type then use 100f
in place of 100.0
).
This is one of those cases where using excess parentheses is actually harmful.
Upvotes: 5