I'm trying to move a RectTransform, triggered when the UI object is clicked. When I set the position in Update, LateUpdate, or Animation, the RectTransform moves as expected. When I try to set position/anchoredPosition/etc. in the OnClick callback, nothing happens (variable is unchanged when I query it).
I have the following gameboard hierachy:
Canvas in Screen space Overlay mode (full size)
- Container: RectTransform object
- MoveObj: gameobjects with RectTransforms and canvas renderer
Container Rect:
MoveObj Rect:
I'm trying to move the MoveObjs to the center of the root canvas, while maintaining the container as the parent. I've tried setting position, localPosition, anchoredPosition, but they don't do anything. After setting that property, when I query it, the values have not changed.
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log($"{this.gameObject.name} - OnPointerClick - state:{this._state}");
(transform as RectTransform).position = offsetMaxTarget; // :(
(transform as RectTransform).localPosition = offsetMaxTarget; // :(
(transform as RectTransform).offsetMin = offsetMinTarget; // :(
(transform as RectTransform).offsetMax = offsetMaxTarget; // :(
(transform as RectTransform).anchoredPosition = targetPosition; // :(
}
SetInsetAndSizeFromParentEdge does change the size of the rect, but does not move the position at all.
(transform as RectTransform).SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 450.0f, 150.0f);
The MoveObjs are instantiated from a prefab:
GameObject newMoveObj = Instantiate(MoveObjPrefab,
new Vector3(Container.transform.position.x, Container.transform.position.y, 2),
Quaternion.identity,
Container.transform);
newMoveObj.transform.localPosition = new Vector3(0, 0, 2);
If I use an Animator, and animate the anchoredPosition and position properties, the objects move exactly as I want them to.
The only property I've set in code that takes an effect, is if I set the pivot, it does actually move. Now that's all well and good, but most of the information I've found says moving the position should at least do something, and the Animation success makes me think that that is the correct way. Before I go mad, why is the positioning not setting correctly in the event handler, but does work in Update?