導入
収集物ごとに一度だけCollectを呼び、合計と地域別の件数を増やします。辞書へ初めて入る地域も0件から加算します。破棄するのは収集物で、トラッカーは残します。
準備と配置
空のGameObjectにRegionTrackerを付け、countLabel TMP_TextとregionPins Image配列を登録します。Imageの名前を地域IDと一致させます。各収集物にはCollectible、Is Trigger Collider、地域IDを設定し、trackerを登録します。PlayerにPlayerタグとRigidbodyまたはCharacterControllerを付けます。
Unity 6向けの例です。[SerializeField]を付けた参照や設定値をInspectorで登録します。文字の参照には対応するTextMeshProコンポーネントを割り当てます。Canvas内の文字はUI > Text - TextMeshProで作れます。
TriggerにはColliderが必要です。3DのTriggerイベントは少なくとも一方のRigidbodyが必要な組み合わせなので、試験時はPlayerへRigidbodyを付けて確認します。タグは事前に作成し、判定対象のColliderを持つGameObjectへ付けます。
処理の流れ
- 収集物: 地域IDを渡す
- トラッカー: 1件加算
- UI: 合計と地域を更新
完成版
以下は記事内の最小例です。機能の範囲は後述の「この例の範囲」で確認してください。クラスごとに示したファイル名で保存し、それぞれ該当するGameObjectへ付けます。
RegionTracker.cs
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using System.Collections.Generic;
public class RegionTracker : MonoBehaviour
{
[SerializeField]
TMP_Text countLabel;
[SerializeField]
Image[] regionPins;
[SerializeField]
int total = 10;
int found;
readonly Dictionary<string, int> regionFound = new Dictionary<string, int>();
void Start()
{
RefreshUi();
}
public void Collect(string region)
{
regionFound.TryGetValue(region, out int count);
regionFound[region] = count + 1;
found++;
RefreshUi();
}
void RefreshUi()
{
countLabel.text = $"{found} / {total}";
foreach (Image pin in regionPins)
pin.color = regionFound.ContainsKey(pin.name) ? Color.cyan : Color.gray;
}
}
Collectible.cs
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using System.Collections.Generic;
public class Collectible : MonoBehaviour
{
[SerializeField]
RegionTracker tracker;
[SerializeField]
string regionId = "Forest";
bool collected;
void OnTriggerEnter(Collider other)
{
if (collected || !other.CompareTag("Player"))
return;
collected = true;
tracker.Collect(regionId);
Destroy(gameObject);
}
}
Inspectorと呼び出しの接続
登録する参照・設定値: countLabel、regionPins、total、tracker、regionId。
検証用Buttonを作る場合は、On Click()の+からスクリプトを付けたGameObjectを登録し、Collect(string)を選びます。引数がある関数は、各Buttonに渡す値も設定します。コード側でonClickへ登録する例では、Inspectorへ同じ処理を重ねて登録しません。
動作確認
異なる地域の収集物を取って合計が1ずつ増え、対応する地域だけ色が変わることを確認します。
この例の範囲
地域マーカーは「1個以上取得した地域」を示します。地域の全収集物を集めた達成率や保存処理は追加設計が必要です。
まとめ
収集物ごとに一度だけCollectを呼び、合計と地域別の件数を増やします。辞書へ初めて入る地域も0件から加算します。破棄するのは収集物で、トラッカーは残します。
この記事のまとめ
宝箱、図鑑、地域達成率を使って、探索の抜け漏れを減らしながら作業感を強めすぎない見せ方を整理します。