How to Show UI Menu on mouse clicked position on a cube or 3d object ?
Hello all i have a scene in which i have a cube in the middle and my camera is rotating around that cube in a circular manner now what i want is that every time when i click mouse on that cube a little menu should appear but the position of the menu should be same as the position of the place where i clicked on the object please help me
Answer by UnityCoach · Oct 25, 2018 at 10:18 AM
Hi,
if the object has a collider, you can use OnMouseUpAsButton() to detect the click on it.
Then you need to get the mouse position, you can use Input.mousePosition for this.
This position is in screen space, so if you're not running full screen, you'll need to adjust it. Camera.ScreenToViewportPoint() allows you to turn a screen position into a viewport position.
Assuming you reference a RectTransform, being the transform of your UI menu object, and that it's parented to a Canvas that covers the whole screen, you can change its position using RectTransform.anchoredPosition and activate the object.
Something like this :
public class PopUpMenu : MonoBehaviour
{
[SerializeField] RectTransform _menu;
Vector2 _screenSize;
void Start ()
{
_screenSize = new Vector2(Screen.width, Screen.height);
}
void OnMouseUpAsButton ()
{
Vector2 mousePosition = Input.mousePosition;
mousePosition.y -= Screen.height;
_menu.anchoredPosition = Vector2.Scale(Camera.main.ScreenToViewportPoint(mousePosition), _screenSize);
_menu.gameObject.SetActive(true);
}
}
Hope this helps.
Your answer
Follow this Question
Related Questions
Use Prefab as Pause Menu 2 Answers
How to create a back button? 0 Answers
3D Look at Mouse relative to Camera direction 0 Answers
Changing Music On Icon To Off and saving the preference 2 Answers