Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a font for a UI Text in Unity 3D programmatically

Tags:

unity3d

in my game I have a UI Text that I've called "label", and I want to set its font programmatically. I've tried to do this:

label.GetComponent<Text>().font="Arial";

I get an error because the font attribute doesn't want a string but a Font. So how can I set the font to Arial programmatically?

like image 787
nix86 Avatar asked Jun 16 '15 16:06

nix86


People also ask

How do I change the UI text in Unity script?

1) Create a GameObject with a Text component; 2) Create a GameObject with a Button component; 3) Create a GameObject with a component of your custom script; 4) Create the reference in your custom script on the Text component you want to update; 5) Create a public method in your custom script that will be invoked when ...

How do I add UI to text?

To insert a Text UI element, go to the Scene Heirarchy, Create → UI → Text. A new Text element should show up in your Canvas region.


2 Answers

This works:

label.GetComponent<Text> ().font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
like image 95
nix86 Avatar answered Oct 17 '22 12:10

nix86


try to create a public variable of type Font in the editor.

public Font myNewFont;

then you can do something like

label.GetComponent<Text>().font= myNewFont;

Not able to test it, but I think it should work, here's a very similar question... How to change Font type in Unity?

like image 2
Roberto Guajardo Avatar answered Oct 17 '22 13:10

Roberto Guajardo