フォントを動的に切り替えるサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.UI; | |
public class SwitchingFonts : MonoBehaviour { | |
// 切り替えるフォント | |
public Font fontRegular; | |
public Font fontBold; | |
// Textコンポーネントを持つゲームオブジェクト | |
public GameObject textObject; | |
// Textコンポーネントへの参照 | |
Text textComp; | |
// フォントの切り替え時間 | |
float switchingTime = 1.0f; | |
// 経過時間 | |
float elapsedTime; | |
void Start(){ | |
// Textコンポーネントへの参照をキャッシュ | |
textComp = textObject.GetComponent<Text>(); | |
} | |
void Update(){ | |
// 指定した時間が経過していたらフォント切り替えのメソッドを呼ぶ | |
if (CheckSwitchingTime()){ | |
SwitchFont(); | |
} | |
} | |
bool CheckSwitchingTime(){ | |
// 切り替えして良いかどうかのフラグ | |
bool canSwitch = false; | |
// 経過時間の変数に前フレームからの経過時間を加算 | |
elapsedTime += Time.deltaTime; | |
// 切り替えのチェック | |
if (elapsedTime >= switchingTime){ | |
// 切り替え時間が経過していたらフラグをtrueにする | |
canSwitch = true; | |
// 経過時間をリセットする | |
elapsedTime = 0f; | |
} | |
return canSwitch; | |
} | |
void SwitchFont(){ | |
// 現在Textコンポーネントに設定されているフォントで分岐 | |
if (textComp.font == fontRegular){ | |
// テキストの内容をセット | |
textComp.text = "今はBoldのフォント"; | |
// フォントの切り替え | |
textComp.font = fontBold; | |
} else { | |
// テキストの内容をセット | |
textComp.text = "今はRegularのフォント"; | |
// フォントの切り替え | |
textComp.font = fontRegular; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment