How to set Sprite width and height to match parent-object width and height in-code?
I have instantiated a sprite. I have set the sprite as a child of an empty game object ( PARENT ). PARENT has a width and height stored in RectTransform. How can I set the Sprite rect to match the PARENT rect ( I would like the sprite to have the same width and height as the parent object ).
Code
tCardDisplay = GameObject.Find("CardDisplay").transform;
tCardRowPos = GameObject.Find("CardRowPos").transform;
rectCardRowPos = GameObject.Find("CardRowPos").GetComponent<RectTransform>();
GameObject go = new GameObject();
Sprite sp = Instantiate(Resources.Load<Sprite>("card_blank_v000"),
new Vector3(0, 0, 0),
Quaternion.identity);
SpriteRenderer sr = go.AddComponent<SpriteRenderer>();
sr.sprite = sp;
This code loads the Sprite properly. The Sprite is used on multiple screens so I would like to resize it to suit the current screen ( whichever ). Upon Instantiation the Sprite is larger than the PARENT object. I am not sure how to resize the Sprite to match the PARENT object. Thanks for any replies.
,
Answer by I_Am_Err00r · Aug 22, 2019 at 05:16 PM
I don't have Unity and can't give you a solution that is 100% going to work, but in the SpriteRenderer component you can get a value of SpriteRenderer.Bounds.Extents that will give you the size of a sprite, I would have to toy with it to make sure it will work for you, but here is the documentation on that.
Answer by farshids · Sep 08, 2021 at 09:52 PM
Assuming that parent (below) is the game object that includes SpriteRenderer, this is how it worked for me:
var parent = (gameObject.transform as RectTransform);
var sprite = GetComponent<SpriteRenderer>().sprite;
parent.localScale = parent.rect.size / sprite.rect.size * sprite.pixelsPerUnit;
Your answer
![](https://koobas.hobune.stream/wayback/20220612211018im_/https://answers.unity.com/themes/thub/images/avi.jpg)