facebook twitter hatena line email

Unity/Csharp/Dictionary

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

ディクショナリサンプル

空のDictionaryを作成

using System.Collections.Generic;
Dictionary<string, object> myDictionary = new Dictionary<string, object>();

初期値を含めて作成

Dictionary<string, object> myDictionary = new Dictionary<string, object>()
{
    {"key1", "value1"},
    {"key2", 123},
    {"key3", true},
    {"key4", 3.14f}
};

データ追加

using UnityEngine;
using System.Collections.Generic;

public class DictionaryExample : MonoBehaviour
{
    void Start()
    {
        Dictionary<string, object> gameData = new Dictionary<string, object>();
        gameData.Add("playerName", "Player1");
        gameData.Add("score", 1000);
        gameData.Add("isAlive", true);
        gameData.Add("position", new Vector3(1.0f, 2.0f, 3.0f));
        
        // 値にアクセス
        string name = (string)gameData["playerName"];
        int score = (int)gameData["score"];
        Vector3 pos = (Vector3)gameData["position"];
        
        Debug.Log($"Player: {name}, Score: {score}, Position: {pos}");
    }
}

独自クラスディクショナリ

using System.Collections.Generic;
Dictionary<string, Car> cars = new Dictionary<string, Car>();
Car bg1 = new Car("Lexas", 50);
Car bg2 = new Car("Rx8", 100);
cars.Add("Lexas", bg1);
cars.Add("Rx8", bg2);
Car car = cars["Lexas"];

宣言時にデータを入れる場合

Dictionary<string, Car> cars = new Dictionary<string, Car>()
{
    { "Lexas", new Car("Lexas", 50)},
    { "Rx8", new Car("Rx8", 100)},
};

ディクショナリをenumキーで

Dictionary<HogeType, Button> enumDict = new Dictionary<HogeType, Button>();

ディクショナリforeach

foreach(KeyValuePair<HogeType, Button> pair in enumDict)
{
    Debug.Log (pair.Key + " " + pair.Value);
}

ディクショナリのキーの存在判定

if (cars.ContainsKey("Lexas")) {
    // 存在するとき
}

TryGetValueを使うとき

if (cars.TryGetValue("Lexas", out Car carvalue))
{
    return carvalue;
}
return null;

参考:https://docs.microsoft.com/ja-jp/dotnet/api/system.collections.generic.dictionary-2.trygetvalue?view=net-5.0