- Home /
Changing a GUI Button's font in code
So I've been fooling around with the GUI creation tools in Unity, but I've run into a problem. I've found a version of my font that is hollow in the center (just an outline of the letters) and another that is filled in. I want to have the font change to the filled in version when hovered over. I'm not sure how to access the button's font to change it though. Is there any way or am I going to have to just make the buttons images.
I've pretty much settled on that solution but now I'm extremely curious.
Are you using OnGUI or new UI code? There are many examples for OnGUI such as
http://answers.unity3d.com/questions/1024090/changing-a-gui-buttons-font-in-code.html
Answer by legion_44 · Aug 08, 2015 at 02:06 PM
The Text on button is actually child GameObject with Text component on it. To change its font on hover, create a script that implements UnityEngine.EventSystems.IPointerEnterHandler and IPointerExitHandler. Script can look like this:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
// Place on button
public class FontChangeOnHover : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
// Fields
public Text theText; // we will change it's font
public Font normalFont;
public Font hoverFont;
public void OnPointerEnter (PointerEventData eventData)
{
theText.font = hoverFont;
}
public void OnPointerExit (PointerEventData eventData)
{
theText.font = normalFont;
}
}
Now just assign the Button's Text and Fonts variables.