Skip to content

Instantly share code, notes, and snippets.

@todorok1
Last active June 8, 2018 15:05
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 todorok1/001c71c6122fba34af706b12009e3c7f to your computer and use it in GitHub Desktop.
Save todorok1/001c71c6122fba34af706b12009e3c7f to your computer and use it in GitHub Desktop.
フォントを動的に切り替えるサンプルコード
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