How to copy a recttransform?

Hello, i have an object with a recttransform and i like to copy it to a different gameobject so it will have the exact rect variables how can i do this the best?

Ehm, in editor or in game?
In editor you need to copy the rect transform component and past only the values on another.
In game you need to create a script that do the exact same thing. Remember to add “using UnityEngine.UI” for use the Rect Transform component

Easiest way to be to duplicate the thing you want to copy with Instantiate

RoMax with a script…

i have a gameobject i want to copy the rect stuff to it. just instantiate the object the rect comes from does not work since the new object is an instance of something with some stuff on it. I “solved” it by make a own function which just copys the basic values it worked so far…

RectTransform is not a part of the UnityEngine.UI namespace.

Oh, your right :hushed:

// Create a new UI GameObject like this, you can just add RectTransform only if you want.
obj = new GameObject(layerName, new Type[] { typeof(RectTransform), typeof(CanvasRenderer) } );

// optionally, you can set the Parent using the transform (not the RectTransform)
obj.transform.SetParent(transform, false);

// Get the source and target RectTransform components
RectTransform rectTransform = GetComponent<RectTransform>();
RectTransform objRectTransform = obj.GetComponent<RectTransform>();

// These four properties are to be copied
objRectTransform.anchorMin = rectTransform.anchorMin;
objRectTransform.anchorMax = rectTransform.anchorMax;
objRectTransform.anchoredPosition = rectTransform.anchoredPosition;
objRectTransform.sizeDelta = rectTransform.sizeDelta;
14 Likes

Hi, I’ve been dealing with this issue today and just wanted to point out that within the properties to be copied you should also account for the pivot:

objRectTransform.pivot= rectTransform.pivot;

3 Likes