「ユーザーがゲームを進めていくと、選べる項目が増えていく」というメニュー画面を作りたい。アンロック形式なので、初めから全てのボタンをHierarchy上に置いておき、未開放分は非アクティブにしておく形式を取ることにする。
表示内容はScriptableObjectの内容に追従して欲しい。ただ、表示の変更はゲーム再生中だけではなく編集中にも行われて欲しい。このような場合には、
[ExecuteInEditMode] を使うと良い。(
参考 )
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 UnityEngine;
using UnityEngine.UI;
using System.Collections;
[ExecuteInEditMode]
public class CategoryButtonText : MonoBehaviour {
[SerializeField] private int id = 1;
[SerializeField] private CategoryDB cDB;
private int oldID = 1;
void Update () {
//IDに変更がない場合は処理をしない
if (id == oldID || id == 0) return;
//デバッグ用のブール代数を用意
bool isFound = false;
//検索
foreach (CategoryDB.CategoryData data in cDB.list){
if(data.id == id){
GetComponent<Text>().text = data.name;
isFound = true;
break;
}
}
//IDの更新
oldID = id;
//検索結果をログに表示
if (isFound) {
Debug.Log ("指定IDの内容に変更しました。(CategoryButtonText.cs)");
} else {
Debug.Log ("指定のIDは見つかりませんでした。内容の変更は行われませんでした。(CategoryButtonText.cs)");
}
}
}
これにより、パラメーターの変更があるとUpdate関数が呼び出され、編集中にボタンの表示内容が変更される。
注意点
Updateはパラメータに変更のあったオブジェクトだけではなく、[ExecuteInEditMode]のUpdateを持つ全てのオブジェクトで実行される。今回の場合で言えばボタンの数だけログが吐き出されるので、IDに変更のあったオブジェクトだけ処理を行うようにした。
inspectorでidを変更する際に一度空欄になるが、このときの値はNullではなく0である。
0 件のコメント:
コメントを投稿