- Home /
When i load sprite from file, the sprite component gets resized, how to avoid it?
So i have an empty 2d Sprite object that i have positioned and sized as i need.
Then i load image into it from code, and the sprite object gets resized to the size of the image. How do i avoid it? I need the loaded image to be the exact size as the sprite object.
Answer by AaronBacon · Dec 11, 2021 at 07:04 PM
So your issue is the Pixels Per Units of the sprites, which can be set for files in the project near the top:
⠀
⠀
So a PPU of 10 will render at twice the size of something with a PPU of 20. What this means is that one way of keeping size consistent is to set the sprite PPUs so that they will always render at the same scale. However another way you can do it if you cant control the PPU beforehand (Like loading sprites externally) is to resize the object to match the previous fixed sprite like this:
⠀
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoadSprite : MonoBehaviour
{
private Vector3 fixedSize;
private SpriteRenderer spr;
// Awake is called when the script instance is being loaded.
protected void Awake()
{
spr = GetComponent<SpriteRenderer>();
fixedSize = transform.localScale * spr.sprite.pixelsPerUnit;
}
void Load(Sprite sprite)
{
spr.sprite = sprite;
transform.localScale = new Vector3(fixedSize.x/spr.sprite.texture.width,fixedSize.y/spr.sprite.texture.height,1f);
}
}
⠀
So basically just set a fixed size to "remember" on Awake, then resize the sprite Scale using the new dimensions of the sprite every time it's changed.
Your answer
Follow this Question
Related Questions
renderer.enabled doesn't work but coloring does 1 Answer
Why can't the camera render the sprite? 2 Answers
Why doesn't a Sprite Renderer with a Mobile/Diffuse shader work on Android? 1 Answer
2D Sprite Graphics Glitching, Skewing, Flickering, Crazy, Haywire 1 Answer
Issue with swapping Player sprite when health lowers - Not sure how to fix 1 Answer