- Home /
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:
I want to instantiate prefabs inside this UI panel which has its own anchor attributes:
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?
Answer by aphenine · Nov 16, 2016 at 10:58 PM
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.
Your answer
Follow this Question
Related Questions
Is there a way to make a Dotted Curved line in Unity for UI? 0 Answers
Move UI object to center of screen while maintaining its parenting 2 Answers
Scrolling UI runtime problem. 0 Answers
Enable prefabs in different scene on level load 2 Answers
How to convert unity editor GUI functions to something that can be used in game? 0 Answers