例えば、UIで画像の上に文字を表示するように作って、それをゴールした時に少しずつ不透明にしていって、表示するようにしたいときのスクリプトの作り方です。
完成動作
作り方
UIを作成
画像の上にテキストが重なるように作成
1.UI→Imageを作成

2.Imageの子の要素となるようにTextを作成

※Unityの新しめのバージョンではTextはUI→Legacyの中にあります。

以下のような状態になる。

3.ImageとTextの位置を中央にする。(Pos X,Y,Zを0にする)


4.例としてTextの文字をゴールにし、Alignmentで上下・左右中央寄せにする


5.画面の中央にImageとTextが表示されていることを確認(例なので、実際は端っこでもどこでも良い)

透明度をスクリプトから変更するための準備
1.透明度をまとめて変更したいUIの一番上の親(今回はImage)に”Canvas Group”コンポーネントを追加


※Alphaの値を変えることで透明度を変えることができる。
透明度を変更するスクリプトを作成
1.ChangeAlpha.csという名前のスクリプトを作成して、以下のコードを記載する。
using UnityEngine;
// CanvasGroupコンポーネントがアタッチされていない場合、アタッチ
[RequireComponent(typeof(CanvasGroup))]
public class ChangeAlpha : MonoBehaviour
{
// フェードさせる時間を設定
[SerializeField]
[Tooltip("フェードさせる時間(秒)")]
private float fadeTime=1f;
// 経過時間を取得
private float timer;
// Start is called before the first frame update
void Start()
{
// このゲームオブジェクトのCanvasGroupコンポーネントを取得して、
// alpha値を0(透明)にする。
this.gameObject.GetComponent<CanvasGroup>().alpha = 0;
}
// Update is called once per frame
void Update()
{
// 経過時間を加算
timer += Time.deltaTime;
// 経過時間をfadeTimeで割った値をalphaに入れる
// ※alpha値は1(不透明)が最大。
this.gameObject.GetComponent<CanvasGroup>().alpha = timer / fadeTime;
}
}
スクリプトを”Canvas Group”コンポーネントをアタッチしたGameObjectにアタッチ
1.ChangeAlpha.csをImageにアタッチ


完成
これでゲームを開始すると、少しずつ画像とテキストがフェードインしてくる。
フェードインが完了するまでの時間を変更したい場合は、”Change Alpha”コンポーネントの”Fade Time”を変更する。
コメント