0
votes

I have a square sprite (width == height) and I want to scale it so that both width and height are exactly one fifth of the width of screen.

To find the desired pixel width I do:

float desiredWidthPixels = Screen.width * 0.2f;
float desiredHeightPixels = Screen.width * 0.2f;

How do I apply these values to the sprite?

1
If you want the a more exact value I would suggest you consider using doubles of a float. As for your question, take a look at this document.CalebB
thanks, but my problem is not about making sprite animations, I just need to know how to apply those values to the sprite so that it gets resized to desired width/height (I need to do it from script)Luca Pagliuca
I take it you didn't read the article then?CalebB
I did, and I thank you for the good read, but that's not what I need; I just need to resize the sprite from script so that its width and height are one fifth of the screen, on all the possible screen sizes and resolutionsLuca Pagliuca

1 Answers

1
votes

It depends if your camera is Orthographic or not.

You will have to Scale the object up or down, depending on its original size.

 float cameraHeight = Camera.main.orthographicSize * 2;
 float cameraWidth = cameraHeight * Screen.width / Screen.height; // cameraHeight * aspect ratio

 gameObject.transform.localScale = Vector3.one * cameraHeight / 5.0f;

The code goes into a Script file attached to the GameObject (in your case the sprite) since gameObject means the Game Object it is on. If you are doing it from another script file then you will need to find the object first in the tree before scaling it.