M
M
max_vr2017-04-28 22:27:07
C++ / C#
max_vr, 2017-04-28 22:27:07

What is the correct way to assign parent object after Instantiate in unity?

Good evening!
Such a task: I am working now with drag & drop through an event trigger, it is necessary that at the beginning of the drag a copy of the object is created, in a certain branch of the hierarchy, which will follow the cursor.
I do it like this:

public void onModelBeginDrag(GameObject model){
    movedModel =  Instantiate (model as GameObject);
    movedModel.transform.SetParent (wall1.transform);

public void onModelDrag(){
    movedModel.transform.position = Input.mousePosition;
  }
  }

After that, a strange bug appears (rather a consequence of the curvature of my hands):
In the inspector, the coordinates of the object are considered relative to the anchors (as it should be), but at the same time, when I try to get the coordinates from the code using object.transform.position , they are considered from the left bottom corner of the screen. What did I do wrong? On the screen, the coordinates of the same object in the inspector, and obtained from transform.posotion b3387e9e2b814e05ac41d1bfa1ead350.png
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniil Basmanov, 2017-04-29
@max_vr

Input.mousePosition returns the mouse coordinates in pixels and depends on the screen resolution. Depending on the CanvasScaler settings, these coordinates may not match the canvas's local coordinates. To get the correct mouse position, use RectTransformUtility.ScreenPointToWorldPointInRectangle and RectTransformUtility.ScreenPointToLocalPointInRectangle . And it's even better not to access the mouse directly, but to use the event system through IDragHandler , then the coordinates will always be correct, the documentation even has an example with drag and drop.

G
GavriKos, 2017-04-28
@GavriKos

Well, because transform.position returns from the bottom left corner. And in the inspector you look not at transform, but at rectTransform - these are different data structures, and the values ​​are also different.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question