opaotti
opaotti

Reputation: 1

Unity Prefab Child set coordinates to x=0 y=0

I have a problem.

I have created a prefab in unity that has a child. I want to place this child on the position x=0, y=0 of the canvas, but it is always positioned on the centre of the parent. How can I move it (with code if possible) to the coordinates of the canvas?

its not in the centre of the canvas

Appreciate all the helps.

i tried everything i could think of, but in the end it always came out what i expected: the centre of the parent

Upvotes: 0

Views: 323

Answers (2)

Part-time Maniac
Part-time Maniac

Reputation: 61

I'm assuming by "x=0, y=0", you mean the center of the canvas. Given that you want to set the object's position relative to another object that is not its direct parent, you will have to do some tricks.

The easiest way is to parent the object to the canvas, set its anchoredPosition to (0, 0, 0), then parent it back to its original parent:

public class Test : MonoBehaviour
{
    [SerializeField] private Canvas canvas;
    [SerializeField] private Transform parent;
    
    private RectTransform rectTransform;

    private void Start()
    {
        rectTransform = GetComponent<RectTransform>();
        
        transform.SetParent(canvas.transform);
        rectTransform.anchoredPosition = Vector3.zero;
        transform.SetParent(parent);
    }
}

The harder (and probably better) way is to calculate the canvas's coners' position in world space using GetWorldCorners(), then set the object's position accordingly:

public class Test : MonoBehaviour
{
    [SerializeField] private Canvas canvas;
    
    private void Start()
    {
        Vector3[] canvasCorners = new Vector3[4];
        canvas.GetComponent<RectTransform>().GetWorldCorners(canvasCorners);

        // Here I'm using the middle point of the bottom-left and top-right corner to set the position
        transform.position = (canvasCorners[0] + canvasCorners[2]) / 2;
    }
}

Upvotes: 0

carnoteng
carnoteng

Reputation: 29

I don't think i understand your question but, if you want to move the child, you just have to select it on hierarchy then move it. It will change its position, but on the inspector you will see that, its transform takes the parent as a origin. If you want to move it via script attach a script to child, then use basic movement like transform.Translate = https://docs.unity3d.com/ScriptReference/Transform.Translate.html.

Upvotes: 0

Related Questions