スタート画面でよく点滅するテキストがありますよね。
今回は、その点滅テキストの作り方を紹介していきたいと思います。
イメージ図↓

準備
まずは、テキストを用意
ヒエラルキーで右クリック>UI>Text-TextMeshPro

普通のTextを使う場合はヒエラルキーで右クリック>UI>Legacy>Text

画面サイズに適応させるために、「Canvas Scaler」の「UI Scale Mode」を「Scale With Screen Size」に変更しておきましょう。

あとは色や位置を調整すれば準備は完了

点滅させるスクリプト
TextMeshPro用のソースコード
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class 点滅 : MonoBehaviour
{
float speed = 1.0f;
float time;
TMP_Text text;
void Start()
{
text = gameObject.GetComponent<TMP_Text>();
}
// Update is called once per frame
void Update()
{
text.color = GetAlphaColor(text.color);
}
Color GetAlphaColor(Color color)
{
time += Time.deltaTime * 3.5f * speed;
color.a = Mathf.Sin(time);
return color;
}
普通のText用のソースコード
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class 点滅普通 : MonoBehaviour
{
float time;
float speed = 1.0f;
Text text;
void Start()
{
text = gameObject.GetComponent<Text>();
}
void Update()
{
text.color = GetAlphaColor(text.color);
}
Color GetAlphaColor(Color color)
{
time += Time.deltaTime * 3.5f * speed;
color.a = Mathf.Sin(time);
return color;
}
}
このソースコードをTextにアタッチします。

これで実行してみましょう。
できました!
スクリプトの簡単な説明
重要なのはこの関数
Color GetAlphaColor(Color color)
{
time += Time.deltaTime * 3.5f * speed;
color.a = Mathf.Sin(time);
return color;
}
ここでは、テキストのアルファ値をMathF.Sin関数を使って周期的に「0→1」「1→0」をさせています。
これによりテキストが透明になったりもとにもだったりが可能になります。
そして、その値を返り値としてUpdateのtext.colorに返しているわけですね。
まとめ
以外にも簡単にできましたね。
この機能をキャラクターの点滅にも使ってみたいです。
コメント