Kaito Kid
Kaito Kid

Reputation: 1063

Convert a Transform to a RectTransform

In my Unity project, I am creating objects dynamically through scripts.

var btnExit = new GameObject("Player " + ID + "'s Exit Button");
btnExit.transform.SetParent(UI.transform);

I need to set the anchors and pivot of the object. I should be able to do that using its RectTransform component, as I do it when I create objects in the scene editor.

myRectTransform.anchorMin = new Vector2(1, 0);
myRectTransform.anchorMax = new Vector2(0, 1);
myRectTransform.pivot = new Vector2(0.5f, 0.5f);

But the object's transform component is not a RectTransform, just the normal Transform. So I can't cast it to use those properties I need.

RectTransform myRectTransform = (RectTransform)btnExit.transform;

So how can I properly use the power of the RectTransform class on an object that I initialise through scripts instead of in the scene editor?

Upvotes: 6

Views: 23367

Answers (3)

Hustlion
Hustlion

Reputation: 2363

You can directly add a RectTransform component to the gameobject, and the Transform component will change to Rect Transform.

For example:

var btnExit = new GameObject("Player " + ID + "'s Exit Button");
btnExit.AddComponent<RectTransform>();

Then the cast will work:

RectTransform myRectTransform = (RectTransform)btnExit.transform;

P.S.

Without adding the component, the above cast will throw error

InvalidCastException: Cannot cast from source type to destination type.

But with the component added, the cast works fine. Above code is tested in Unity 2018.2.5f1 (64bit).

Upvotes: 3

nopunintendo
nopunintendo

Reputation: 149

RectTransform rectTransform = transform.GetComponent<RectTransform>();

RectTransform rectTransform = (transform as RectTransform);

RectTransform rectTransform = (RectTransform)transform;

As long as your object has a RectTransform, these are all valid ways to get the RectTransform from the built-in transform reference.

Upvotes: 14

Programmer
Programmer

Reputation: 125255

You can't cast Transform to RectTransform. That's what GetComponent is use for. Use GetComponent on the btnExit variable and you will be able to get the RectTransform from the Button.

RectTransform myRectTransform =  btnExit.GetComponent<RectTransform>();

Note:

You should only do this after calling SetParent, since SetParent will make Unity automatically attach RectTransform to the btnExit variable if the Parent Object is a UI Object such as Canvas. You can also use AddComponent to attach RectTransform to that GameObject.

If you don't do any of these, you will get null since RectTransform is not attached to the Button .

Upvotes: -1

Related Questions