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

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.