How to set sprite size in pixels?

I’d like to set sprite size in pixels (not in world units) by using scripts. I switched a camera projection to orthographical and tried setting scale in sprite renderer and pixels per unit in sprite to achieve desired size, but the final result is always wrong. Any idea or an example of how should I do it?

My code:

Component map = GameObject.Find("Map").GetComponent<Component>();
        Texture2D texture = Resources.Load<Texture2D>("test");
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0f, 0f), 1); // pixels per unit = 1
        GameObject gameObject = new GameObject();
        SpriteRenderer spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
        spriteRenderer.sprite = sprite;
        gameObject.transform.SetParent(map.transform);
        spriteRenderer.transform.localPosition = new Vector2(0, 0);
        spriteRenderer.size = new Vector2(1, 1);

Main camera inspector screenshot:
131790-s1.png
Canvas inspector screenshot:

From Unity Docs (OrthographicSize) The orthographicSize is half the size of the vertical viewing volume.

With this, if you want to put real pixels size for your sprite renderers:


  1. In the Import Settings, set Pixels
    per Unit
    to 1.

  2. Set the Camera Projection to
    Orthographic.

  3. Set the Camera Orthographic Size to
    half the height of the screen
    height.


That’s of course for testing purpose. If you want it for multilple resolutions you should do it via script. Remember, the orthographic size half the height of the screen height.


If you dont want none of above, you could let the default Pixels Per Unit (100) and default Orthographic size (5). Then via script, scale your world of your desired sprites according to what I mentioned before.

Finally, I got it. I put working code for others who will have a similar problem.

        GameObject map = GameObject.Find("Map");
        Texture2D texture = Resources.Load<Texture2D>("test");
        var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0f, 0f), 1);
        GameObject gameObject = new GameObject();
        SpriteRenderer spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
        spriteRenderer.sprite = sprite;
        gameObject.transform.SetParent(map.transform);
        spriteRenderer.transform.localScale = Vector2.one;

The order is very important. If you change localScale before setting gameObject parent then sprite rendering will be wrong. All settings (camera, canvas) are like on screenshots in the question.