- Home /
Question by
Umai · Nov 21, 2014 at 12:24 PM ·
2dgameobjectsizewidth
Get width and height of Image in Unity 4.6
How can I get the width and height of an Image (or Button etc) in C# code in Unity 4.6?
Specifically, I am instantiating a prefab into a GameObject, and then want to access the width/height from that instance.
GameObject mynewcard = (GameObject)Instantiate(card); // where card is the prefab assigned in the editor to a public member variable.
mynewcard.size.width // nahh
mynewcard.width // no...
Comment
Best Answer
Answer by troien · Nov 22, 2014 at 09:21 AM
If your card is a prefab that has a RectTransform component. You can get the width/height using RectTransform.rect.
To get the RectTransform: (multiple options)
simply cast the transform to RectTransorm,
GameObject mynewcard = (GameObject)Instantiate(card);
RectTransform rt = (RectTransform)mynewcard.transform;
call GetComponent
GameObject mynewcard = (GameObject)Instantiate(card);
RectTransform rt = mynewcard.GetComponent<RectTransform>();
or get the RectTransform from the Image itself.
Image mynewcard = (Image)Instantiate(card); // Don't forget 'using UnityEngine.UI' and card must have a image Component ;)
RectTransform rt = mynewcard.rectTransform;
Then get the width/height
float width = rt.rect.width;
float height = rt.rect.height;
(Unity 4.6.0f2)