How to find width and height of game object, Unity2D

Hi everyone!

I have stacked at my code and I’m not sure how to find details (width & height) of my game object. I tried to set component of RectTransform and tried code like this:

float width = rt.rect.width;     // Here is problem
    float height = rt.rect.height;   // Here is problem
    
    GameObject mynewball = (GameObject)Instantiate(ball);
        RectTransform rt = (RectTransform)mynewball.transform;
    
    width = 100f;
    height = 50f;

My code is not correct so, how can i declare and find my Height and Width of Object through C# ?
So later on i can change size (height & width) through code?

Hello, I would suggest very simple solution:

float width = GetComponent<SpriteRenderer>().bounds.size.x;

I don’t get it, that’s your code? That shouldn’t even compile.

First, you’re using “rt” before declaring it. Second, “rect” is a property that you can get, you can’t modify the values directly. Third, once you write “float width = rt.rect.width” the “width” variable has a copy of the rect’s width, so changing the value of that variable won’t change anything.

Your code to get the width should be in the inverse order:

GameObject mynewball = (GameObject)Instantiate(ball);
RectTransform rt = (RectTransform)mynewball.transform;

float width = rt.rect.width;
float height = rt.rect.height;

If you want to change the width and height manually it depends on the anchors. If the UI element is centered inside the parent then rt.sizeDelta is a Vector2 with rt.sizeDelta.x being the width and rt.sizeDelta.y the height, and to change those values you replace the sizeDelta like this:

rt.sizeDelta = new Vector2(100f, 50f);

If the element is not centered you have to change sizeDelta too, but x and y means something different. Look here: Unity - Scripting API: RectTransform.sizeDelta