Converting transform to RectTransform
In my Unity project, I create objects dynamically through scripts.
var btnExit = new GameObject("Player " + ID + " Exit Button");
btnExit.transform.SetParent(UI.transform);
I need to set anchors and rotation of an object. I should be able to do this using its RectTransform component as I do this 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 transform component of the object is not a RectTransform, but just a normal transform. So I cannot use it to use the properties that I need.
RectTransform myRectTransform = (RectTransform)btnExit.transform;
So how can I properly use the power of the RectTransform class for an object that I initialize through scripts and not in the scene editor?
source to share
You cannot drop Transform
before RectTransform
. It is used for this GetComponent
. Use GetComponent
btnExit in variable and you can get RectTransform
from button.
RectTransform myRectTransform = btnExit.GetComponent<RectTransform>();
Note:
You should only do this after the call SetParent
, as it SetParent
will make Unity automatically attach RectTransform
to a variable btnExit
if the parent is a UI object like Canvas. You can also use GameObject AddComponent
to attach RectTransform
to this.
If you donβt do anything, you will receive null
because you are RectTransform
not attached to Button
.
source to share