- Home /
How to create gradient text
I want to use gradient font in my game for displaying score on top of screen, but without NGUI and 2DToolkit. By searching, I came up with Bitmap Font File. I have used Littera in order to create font files. It generates a .fnt file along with a png file.
I have found this link, telling you how to import these files in unity. But how can I use them? Or Is there any other better method of achieving my goal? Thanks.
Would this gradient effect also be on a single letter? Or is having each letter a different color enough?
Answer by Noxury · May 20, 2017 at 07:07 PM
Attach this script to a text gameobject:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
[AddComponentMenu("UI/Effects/Gradient")]
public class Gradient : BaseMeshEffect {
[SerializeField]
private Color32 topColor = Color.white;
[SerializeField]
private Color32 bottomColor = Color.black;
public override void ModifyMesh(VertexHelper vh){
if (!this.IsActive())
return;
List<UIVertex> vertexList = new List<UIVertex>();
vh.GetUIVertexStream(vertexList);
ModifyVertices(vertexList);
vh.Clear();
vh.AddUIVertexTriangleStream(vertexList);
}
public void ModifyVertices(List<UIVertex> vertexList) {
int count = vertexList.Count;
float bottomY = vertexList[0].position.y;
float topY = vertexList[0].position.y;
for (int i = 1; i < count; i++) {
float y = vertexList[i].position.y;
if (y > topY) {
topY = y;
} else if (y < bottomY) {
bottomY = y;
}
}
float uiElementHeight = topY - bottomY;
for (int i = 0; i < count; i++) {
UIVertex uiVertex = vertexList[i];
uiVertex.color = Color32.Lerp(bottomColor, topColor, (uiVertex.position.y - bottomY) / uiElementHeight);
vertexList[i] = uiVertex;
}
}
}
If you want to combine this with UI/Outline or Shadow make sure this script is sitting above them in the inspector.
Thank you really much for your code, it work perfectly ! Could you just tell me how to make this gradient horizontal and not vertical please ? :)
Never$$anonymous$$d, found it myself, thank you again for your code ! If someone end up here by any chance, you just have to change the position.y by position.x, and if you want something clean, modify all variables names that contain y (topY, bottomY, ...)
Answer by Pendrokar · Jul 25, 2014 at 10:22 AM
It generates a .fnt file along with a png file.
How can I use these or convert them to use in Unity?
You need to convert them to either ".ttf", ".dfont" or .otf format.
Supported Font formats are TrueType Fonts (.ttf or .dfont files) and OpenType Fonts (.otf files). http://docs.unity3d.com/Manual/class-Font.html
Thanks for reply @Pendrokar. As I mentioned a link, it tells you to convert .fnt file to .txt. and assign it to a material. What can i do next?