G
G
Gwinterion2022-02-16 04:47:55
Unity
Gwinterion, 2022-02-16 04:47:55

How to correctly set the position of an object relative to another object?

I have a Container object that I instantiate and then assign a position to it using the SetPosition method

public void SetPosition(GameObject itemButton)
    {
        Vector2 position;
        position.x = itemButton.GetComponent<RectTransform>().transform.position.x;
        position.y = itemButton.GetComponent<RectTransform>().transform.position.y + 50;
        Container.transform.position = position;

    }

I want the Container to appear at the position of the itemButton object with a slight adjustment on the Y axis. The Container's X coordinates are set correctly, but on the Y axis it is far off the screen. If you place it without making an amendment, then everything works fine. What is the problem?620c566927155966780349.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nekit Medvedev, 2022-02-16
@NIKROTOS

I don't understand how this script works, but maybe the problem is that you are confusing screen coordinates with normal ones. Someone had a similar problem.

C
combine1, 2022-02-16
@combine1

In any case, you need to specify the z coordinate
. And it will be easier to do this:

container.transform.position = button.transform.position + (Vector3.up * 50)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question