Place UI element on pointer up position.

Hello.

I have an invisible UI Panel which is streched over canvas and has OnPointerUp method.

It has anchors like this:

76739-1.png

I want to instantiate prefabs inside this UI panel which has its own anchor attributes:

76740-2.png

I want to capture pointers position and instantiate there my UI prefab as my panels child like this:

 public void OnPointerUp(PointerEventData pointer)
 {
        GameObject newUIElement = Instantiate(myprefab) as GameObject;
        newUIElement.transform.SetParent(invisibleParentPanel.transform);
        RectTransform rect = (RectTransform)newUIElement.transform;
        rect.position = pointer.position
 }

My new UI element has very big coordinates which places it far outside. Is there I need to add some new calculations?

I think you may be having anchoring issues.

The position of your added UI element is usually done with respect to its anchor in the parent. Your sub element has an anchor in the middle, which means (0,0) is at the centre of the parent UI. I think the mouse pointer click will measure from the bottom left, meaning you might have to make some adjustments (such as adding RT.sizeDelta/2 to the position of the mouse pointer Vector2, where RT is the parent RectTransform. This would explain why you’re getting massively out of range values.

You may also have some issues with scaling. Beyond that I’m not sure.