Skip to content

Instantly share code, notes, and snippets.

@kobakoto-jy
Created January 21, 2022 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobakoto-jy/dcee520d33ddd5041cde35707d01797e to your computer and use it in GitHub Desktop.
Save kobakoto-jy/dcee520d33ddd5041cde35707d01797e to your computer and use it in GitHub Desktop.
UnityのTextmeshProで文字を左からフェードして表示させるための奴
using UnityEngine;
using TMPro;
namespace TMExtension
{
// Function for TextmeshPro to fade text.
public class TextFadeEffecter : MonoBehaviour
{
[Range(0, 1)]
public float FadePercent = 0;
int streamCount = 0;
TMP_Text m_textMesh;
protected void Reset()
{
m_textMesh = GetComponent<TMP_Text>();
}
protected void OnEnable()
{
m_textMesh = GetComponent<TMP_Text>();
}
protected void OnValidate()
{
var textMesh = GetComponent<TMP_Text>();
if(textMesh != null)
{
Modify(textMesh);
}
}
private void Update()
{
if (m_textMesh == null) return;
Modify(m_textMesh);
}
void Modify(TMP_Text textMesh)
{
var textInfo = textMesh.textInfo;
if (textInfo == null || textInfo.characterCount == 0) return;
streamCount = textInfo.characterCount;
for(int i = 0; i < streamCount; ++i)
{
var charInfo = textInfo.characterInfo[i];
if (!charInfo.isVisible) continue;
int materialIndex = charInfo.materialReferenceIndex;
int vertexIndex = charInfo.vertexIndex;
float f = i / (float)streamCount;
float alpha = 1 - Mathf.Clamp01(f - (FadePercent * 2 - 1.0f));
var col = charInfo.color;
col.a = (byte)(col.a * alpha);
var cols = textInfo.meshInfo[materialIndex].colors32;
for (int k = 0; k < 4; ++k)
{
cols[vertexIndex + k] = col;
}
}
for(int i = 0; i < textInfo.materialCount; ++i)
{
if (textInfo.meshInfo[i].mesh == null) continue;
textInfo.meshInfo[i].mesh.colors32 = textInfo.meshInfo[i].colors32;
textMesh.UpdateGeometry(textInfo.meshInfo[i].mesh, i);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment