【Unity】Buttonを使ったDictionaryの機能サンプル
スポンサーリンク
C#のDictionary、keyとvalueを一体化して登録することができます。
ポイントはDictionaryのkey に使用する型は string や int 型などの普遍的でデータ容量が軽いものにしてください。
たまにkey に Unity.Objectの「Shader」や、あろうことか自作したClass を設定している人がいます。。。
そのような恐ろしいことを起こさないようにして行きたいですね・・・・・。
Buttonを利用してDictionaryの動作を確認しよう。
今回は以下のサンプルコードを作成します。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ItemBtn : MonoBehaviour { // Itemを保管するDictionary private Dictionary<int, string> mItemDictionary = new Dictionary<int, string> (); private int mDicCnt; // Start is called before the first frame update public void BtnA () { this.mItemDictionary.Add (this.mDicCnt, "A"); this.mDicCnt++; } public void BtnB () { this.mItemDictionary.Add (this.mDicCnt, "B"); this.mDicCnt++; } public void BtnC () { this.mItemDictionary.Add (this.mDicCnt, "C"); this.mDicCnt++; } // Dictionaryの値を表示する public void ViewDictionaryBtn () { foreach (var dic in this.mItemDictionary) { Debug.Log ($"dic.key {dic.Key} :: dic.Value {dic.Value}"); } this.mItemDictionary.Clear (); this.mDicCnt = 0; } }
それぞれのBtn,A,B,C 関数を 上の画像の ABCボタンにそれぞれアタッチします。
最後の結果ボタンには「ViewDictionaryBtn」関数をアタッチします。
ソースコードの内容はボタンを押すごとにmDicCntの値がKeyとして、関数ごとに設定してある文字がValueとしてDictionaryに登録されます。
ViewDictionaryBtnではそれまでに登録した値を全て表記することになります。
実際に起動してみると上記のような結果になります。
Dictionaryはデータ管理などで使用することが多い機能のため、使い方を理解しておくととても役立ちます。