Make text/canvas follow or show where the cursor is.

Hi there

I have a script which makes text appear when I mouse over a certain object. But instead of the text appearing on a fixed place in the camera view I would like it to appear right next to my cursor.

I found this (outdated) tutorial which looks like the very thing I need but it is not C# but Javascript. Has someone a way of achieving this?

this is the script from the tutorial

var text = "PUT TEXT HERE";
private var currentToolTipText = "";
private var guiStyleFore : GUIStyle;
private var guiStyleBack : GUIStyle;
function Start()
{
     guiStyleFore = new GUIStyle();
     guiStyleFore.normal.textColor = Color.white; 
     guiStyleFore.alignment = TextAnchor.UpperCenter ;
     guiStyleFore.wordWrap = true;
     guiStyleBack = new GUIStyle();
     guiStyleBack.normal.textColor = Color.black; 
     guiStyleBack.alignment = TextAnchor.UpperCenter ;
     guiStyleBack.wordWrap = true;
}
function OnMouseEnter ()
{
     currentToolTipText = text;
}
function OnMouseExit ()
{
     currentToolTipText = "";
}
function OnGUI()
{
     if (currentToolTipText != "")
     {
         var x = Event.current.mousePosition.x;
         var y = Event.current.mousePosition.y;
         GUI.Label (Rect (x-149,y+40,300,60), currentToolTipText, guiStyleBack);
         GUI.Label (Rect (x-150,y+40,300,60), currentToolTipText, guiStyleFore);
     }
}

Well, this uses ongui, which you might not want to use.

If you go with the newer UI system, you still can get the basic idea. When you mouse over something, set a bool to true like displayTooltip. Then in Update, you’ll want to get the mouseposition, use this to offset the tooltip and set the tooltip position with it.

You can get mouseposition with input.mouseposition Unity - Scripting API: Input.mousePosition

1 Like

thank you! I got it to work :slight_smile:

public string text = “Hey there”;
public string currentToolTipText = “”;
public GUIStyle guiStyleFore;
private GUIStyle guiStyleBack;
void Start()
{
guiStyleFore = new GUIStyle();
guiStyleFore.normal.textColor = Color.green;
guiStyleFore.alignment = TextAnchor.UpperCenter;
guiStyleFore.wordWrap = true;
guiStyleBack = new GUIStyle();
guiStyleBack.normal.textColor = Color.black;
guiStyleBack.alignment = TextAnchor.UpperCenter;
guiStyleBack.wordWrap = true;

}
void OnMouseEnter()
{
currentToolTipText = text;

}
void OnMouseExit()
{
currentToolTipText = “”;
}
void OnGUI()
{
if (currentToolTipText != “”)
{
float x = Event.current.mousePosition.x;
float y = Event.current.mousePosition.y;
GUI.Label(new Rect(x - 149, y + 40, 300, 60), currentToolTipText, guiStyleBack);
GUI.Label(new Rect(x - 150, y + 40, 300, 60), currentToolTipText, guiStyleFore);
}
}

This is the code which is in C#.