今回はスタート画面でよく見かける点滅する文字の作り方を記述したいと思います。
準備
まずは文字やcanvasを用意します。
ヒエラルキーウィンドウで UI>Legacy>TextでCanvasとテキストを生成します。


次にCanvasのインスペクターを見ましょう。
その中の、Canvas ScalerコンポーネントのUI Scale Modeという項目があります。
Constant Pixel SizeからScale With Screen Sizeに変更します。

これで画面の大きさに対応した文字の大きさになります。
文字が小さいので大きくしましょう。


大きくしましたが文字が粗いですね。
これを直していきましょう。
文字(Text)のインスペクターで各項目の値をこのように変更します。

変更することでこのようにきれいになります。

きれいにするポイントは「Scale」を小さくし、「FontSize」を大きくすることです。
これで準備は完了です。
点滅スクリプト
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BlinkerScript : MonoBehaviour
{
public float speed = 1.0f;
private float time;
private Text text;
void Start()
{
text = this.gameObject.GetComponent<Text>();
}
void Update()
{
text.color = GetTextColorAlpha(text.color);
}
Color GetTextColorAlpha(Color color)
{
time += Time.deltaTime * speed * 5.0f;
color.a = Mathf.Sin(time);
return color;
}
}
このスクリプトを文字(Text)にアタッチしましょう。

これで実行をしてみると
点滅する文字の完成です!
スクリプトのポイント
このスクリプトで重要な部分はこのGetTextColorAlpha関数
Color GetTextColorAlpha(Color color)
{
time += Time.deltaTime * speed * 5.0f;
color.a = Mathf.Sin(time);
return color;
}
この関数では文字のアルファ値をMath.Sinを使い周期的に変化させ、その値を返り値としてUpdateに返していきます。
void Update()
{
text.color = GetTextColorAlpha(text.color);
}
まとめ
いかがだったでしょうか?
この点滅はキャラクターが攻撃を受けた時の演出などにも使えそうですね。
コメント