I found strange behaviour when I was trying to set position.

I have this code:

private const float BaseY = -45f;
private const float BaseX = 12.5f;
var tile = new WorldTile(playableWorld.Name)
    WorldName = playableWorld.Name, 
    ServerState = GameServerState.Offline
tile.Instance.transform.SetParent(gameObject.transform, false);
tile.Instance.transform.localPosition = new Vector3(BaseX, BaseY, 0)

Where the WorldTile is just wrapper class around creating GameObject, everywhere else is this working - position is perfectly set witihin parent, but when I try here to set the local position, it is not set on [12.5, -45, 0], it is set to [12.5, -295, 0].

I got this structure in Canvas, where CreatedList is element with predefined height of 500, it seems like unity is trying to center the element and then add my position to it..

If I change the height of the parent element to zero, it has the position I set.


Why is that happening when parent object has height?

I am creating object from prefab, which I set to the parent element. Here I want the created object to be exactly on Y -45px from top. How to achieve this?

  • \$\begingroup\$ The position shown in the RectTransform inspector is the anchoredPosition, not the localPosition you'd set on a non-UI object. \$\endgroup\$ – DMGregory Jul 31 at 13:38
  • \$\begingroup\$ @DMGregory Ok, found whats happening here, the CreatedList had set height to 500, from default. In another plac, there is difference, I am changing the height of parent after all elements are placed. Ok, here I don't need the height to be set, but I am wondering, If I have a parent with predefined height, how to set element on exact position here? \$\endgroup\$ – Zechy Jul 31 at 13:48
  • \$\begingroup\$ Want to edit your question to ask that? Make sure you're specific about what "set element on exact position" means - from what reference point are we measuring the desired position, or what specific layout appearance are we trying to create? \$\endgroup\$ – DMGregory Jul 31 at 14:02
  • \$\begingroup\$ @DMGregory Edited, exact position is meant in the parent element, where I want it to -45 down from the top line. \$\endgroup\$ – Zechy Jul 31 at 14:19
  • 3
    \$\begingroup\$ @Zechy "one below another"? Easy: Vertical Layout Group or Grid Layout Group. \$\endgroup\$ – Philipp Jul 31 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.