Search code examples
unity-game-enginetexturesspriteprojection

Unity Correct Sprite/Texture Width Height


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!


Solution

  • 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;