Sometimes you may create a new UI element in script and want to set it’s position etc.
I wrote a quick extension method to allow me to stretch a newly created component to that of it’s parent:
public static class Extensions
{
public static void StretchRectTransform(this Transform value)
{
RectTransform rt = value as RectTransform;
if (rt == null) return;
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.sizeDelta = Vector2.zero;
rt.localScale = Vector3.one;
}
}
Which I used as follows:
public static void Add(GameObject sel)
{
GameObject go = new GameObject(sel.name+"_HL");
go.transform.SetParent(sel.transform);
go.transform.StretchRectTransform();
image = go.AddComponent<Image>();
}
However I quickly found that the cast of a Transform to a RectTransform did not work in this scenario, as it turns out the RectTransform does not yet exist. I’m not sure when it begins to exist however a quick look at the docs and I noticed it’s a Component so modified my function to add it if it did not exist:
public static void StretchRectTransform(this Transform value)
{
RectTransform rt = value as RectTransform;
if (rt == null)
{
rt = value.gameObject.AddComponent<RectTransform>(); // Add a RectTransform if it does not exist
}
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.sizeDelta = Vector2.zero;
rt.localScale = Vector3.one;
}
This now works as expected. I assume adding the RectTransform replaces the original Transform, I’ve not found any docs on this so if anyone knows better please share!