Search Unity

Can you have a UI Canvas/Panel appear above a mouse cursor?

Discussion in 'UGUI & TextMesh Pro' started by frankmat, Aug 14, 2016.

  1. frankmat

    frankmat

    Joined:
    Sep 14, 2013
    Posts:
    42
    Hi,

    I'm really frustrated with this one... and I am guessing (hoping) it's an easy answer.

    I have a panel with 2 buttons... at the moment they appear above the head of the player whenever I click on an interactable object like the newspaper on the floor. Is there any way I can have this canvas appear right next to the cursor?

     
  2. IzzySoft

    IzzySoft

    Joined:
    Feb 11, 2013
    Posts:
    376
  3. McMayhem

    McMayhem

    Joined:
    Aug 24, 2011
    Posts:
    443
    You need to convert your mouse position to canvas space. Are you using a World, Camera or Overlay canvas? This will change what methods you need to get that information.

    Overlay Canvas: use RectTransformUtility.ScreenPointToLocalPointInRectangle just remember to set the "cam" parameter to null. Also, you'll need to pass a reference to the main Rect of your UI. Should be the Canvas or whatever rect covers the entire screen.

    For a world/camera space canvas the process is the same to get the mouse position, but you'll need to also be able to set the position of your UI in order to anchor it to the mouse. To do that, you first need to use RectTransformUtility.WorldToScreenPoint (undocumented) and then go from screen space to canvas space using the above ScreenPointToLocalPointInRectangle method.
     
  4. frankmat

    frankmat

    Joined:
    Sep 14, 2013
    Posts:
    42
    I am using Screen Overlay Canvas.
     
  5. frankmat

    frankmat

    Joined:
    Sep 14, 2013
    Posts:
    42