- Home /
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: Canvas inspector screenshot:
Could you post your code? The approach sounds fine to me, maybe we'll find a bug :)
Answer by bpaynom · Jan 23, 2019 at 01:15 PM
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:
In the Import Settings, set Pixels per Unit to 1.
Set the Camera Projection to Orthographic.
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.
Answer by sndark50 · Jan 25, 2019 at 11:48 AM
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.
Your answer
Follow this Question
Related Questions
keep sprite same size when changing 1 Answer
Why is my sprite not the original resolution? 2 Answers
SpriteRender's sprite not changing 1 Answer