Hello everyone, I want to have a button to purchase an item, but to save space i would like to not show all the stats of that item. Thought the aproach many games have taken to have it so when you place your cursor over a certain button it gives you a box with stats or a description of sort. Thing is the only way I can think of is to check if the cursor is in a certain x, y coordinate in the screen it will create a box. This though, seems awefully complicated, so i was wondering if there´s a better way to do this? I apreciate all your time and thanks in advanced.
First of all, to check if a cursor in over a button, you can just use Rect.Contains:
if(buttonRect.Contains(new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y), true)) {
//
}
Now for the second part of your question. You could create a custom Label, window, or whatever with the needed inormation in it at your mouse position, or any other position on screen, whenever the buttonRect.Contains check is true.
You can also use Unity’s built-in ToolTip function which automatically shows a box whenever your cursor is above any GUI element that has GUIContent which in turn has a tooltip string specified:
if(GUI.Button(buttonRect, new GUIContent("button string", buttonTexture, "ToolTip string"))) {
}
You make the Tooltip show up by calling this code inside your OnGUI() function:
if (!String.IsNullOrEmpty(GUI.tooltip)) {
GUIContent tooltipContent = new GUIContent(GUI.tooltip);
GUIStyle style = new GUIStyle(GUI.skin.textArea);
style.wordWrap = true;
float toolTipHeight = style.CalcHeight(tooltipContent, 200f);
float toolTipHeight2 = GUI.skin.label.CalcHeight(tooltipContent, 200f);
Vector2 tooltipPos;
if(Input.mousePosition.x > Screen.width - 200) {
tooltipPos.x = Input.mousePosition.x - 200 + 16;
}
else {
tooltipPos.x = Input.mousePosition.x + 16;
}
if(Input.mousePosition.y < toolTipHeight) {
tooltipPos.y = Screen.height - Input.mousePosition.y - toolTipHeight + 16;
}
else {
tooltipPos.y = Screen.height - Input.mousePosition.y + 16;
}
//the actual tooltip
GUI.Label(new Rect(tooltipPos.x, tooltipPos.y, 200, toolTipHeight), GUI.tooltip, "Tooltip");
}
Note that only the last line of code actually deals with showing the tooltip; the rest above it is additional but very useful code that a) makes sure that the tooltip box is always completely on screen and b) resizes it’s height dynamically depending on the string size (without this, the text would just be cut at some point).
Are you using UI or legacy?
With the UI tools you simply add an event trigger to your button, add OnPointerEnter and OnPointerExit. Add a listener to each to display and hide your Tool Tip.