0

I discovered something interesting about Unity Sprite and textures (Texture2D). I crated a 50x50 .png and render it in Unity by attaching to a GameObject and using SpriteRenderer.

What I realized, whenever I call a Unity related method (sprite.texture.width, sprite.rect.width, sprite.textureRect.width, etc.), it always return 50. However, the real size of the image turns into 24x24 or 12x12 depending on the resolution on my screen.

Of course, this is no big surprise since the projection, etc. is applied before Unity render the things on the screen; however, the interesting part I couldn't find any method or easy way to get the size of the Sprite after the projection is applied.

I can still make my own projection to come up with the related size; however, I would like to know whether there is an easier way to get this information.

Thank you!

4
  • That's...not an easy question to answer. The image could be inside a transform with a scale applied, etc etc. But you can convert from scene units to screen coordinates. So if you know where the corners are, you can do Camera.main.WorldToScreenPoint(corner) can calculate from that. May 23, 2017 at 20:09
  • I could be wrong, but the 'real' size of the image that is rendered depends on your screen resolution, the camera size and the PPU value of the sprite.
    – Ian H.
    May 23, 2017 at 20:40
  • @Draco18s it's not working well. I tried with sprite.rect.max to world space and it returned (-7.3, -4.0) instead (-4.166, -4.166)
    – ciyo
    May 23, 2017 at 20:42
  • sprite.rect.max is UV coordinates of the sprite in its underlying texture, they are completely and utterly the wrong thing to use here. You need the corners of the sprite's RectTransform May 23, 2017 at 20:47

1 Answer 1

0

The way @Draco18s mentioned seems the only way to solve this problem.

So, I crated a Prefab GameObject containing RectTransform and SpriteRenderer, and got the width and height as below:

GameObject twoSide = Instantiate(Resources.Load(mFilePath + "Locater")) as GameObject;

twoSide.GetComponent<RectTransform>().position = Camera.main.ScreenToWorldPoint (new Vector3 (0, 0, 1));
twoSide.GetComponent<RectTransform> ().pivot = new Vector2 (0f, 0f);    // RectTransform should have the same pivot location with Sprite

float width = twoSide.GetComponent<RectTransform> ().offsetMax.x - twoSide.GetComponent<RectTransform> ().offsetMin.x;
float height = twoSide.GetComponent<RectTransform> ().offsetMax.y - twoSide.GetComponent<RectTransform> ().offsetMin.y;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.