Question by
ChangBroot · Aug 16, 2020 at 02:30 PM ·
spritespriterenderersprite renderer
Change sprite size programmatically
I have a game object and I want the player to be able to change skin (spriterendere) of the game object. There are two sprites - 200x200 (let's call this sprite A) and 300x300 (let's call this sprite B) pixels. I want to change the game object or sprite to appear the same size on the screen, regardless of which skin they choose. I have tried the following, but none of them work. I tried to set the transform.localscale of the game object to 1 and 1 (x, y), but both sprites appear difference size.
Here are what I have done so far:
ballWidth = transform.localScale.x;
ballHeight = transform.localScale.y;
Debug.Log("Ball width and height: " + ballWidth + " " + ballHeight);
if (SelectSkinButton.isSkinSelected) {
gameObject.GetComponent<SpriteRenderer>().sprite = SelectSkinButton.currentSkin;
Vector2 spriteSize = GetComponent<SpriteRenderer>().sprite.bounds.extents;
gameObject.transform.localScale = new Vector2(1, 1);
//transform.localScale = new Vector2(ballWidth, ballHeight);
//gameObject.GetComponent<SpriteRenderer>().size = new Vector2(0.5f, 0.5f);
//gameObject.GetComponent<SpriteRenderer>().transform.localScale = new Vector2(0.5f, 0.5f);
//gameObject.transform.localScale = new Vector2(spriteSize.x, spriteSize.y);
GetComponent<CircleCollider2D>().radius = spriteSize.x;
Debug.Log("Sprite width and height: " + spriteSize.x + " " + spriteSize.y);
}
Any help is greatly appreciated.
Comment