0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Unity databaseを使う

Posted at

databaseとは

たくさんの同じ属性をもつ物を管理する方法

やり方

databaseはScriptableObjectを利用します。ScriptableObjectについては詳しくは別の記事を参照。

まずはスクリプトを2つ作る。
同じ属性を表すスクリプトと
それを格納するデータベース用のスクリプト

具体的にはやさいと、野菜を格納する野菜入れを1つずつ作る。
image.png

using UnityEngine;

//やさい
[CreateAssetMenu(fileName = "NewVegetable", menuName = "Vegetable Database/Vegetable", order = 1)]
public class Vegetable : ScriptableObject
{
    public int id;
    public string vegetableName;
    public float price;
}

using System.Collections.Generic;
using UnityEngine;

//やさい入れ
[CreateAssetMenu(fileName = "VegetableDatabase", menuName = "Vegetable Database/Database", order = 2)]
public class VegetableDatabase : ScriptableObject
{
    public List<Vegetable> vegetables;

    public Vegetable GetVegetableById(int id)
    {
        foreach (Vegetable vegetable in vegetables)
        {
            if (vegetable.id == id)
            {
                return vegetable;
            }
        }
        Debug.LogWarning("Vegetable with ID " + id + " not found.");
        return null;
    }
}

やさい入れにはidで検索できるメソッドも追加。
これで準備OK
ScritableObjectを右クリックから作成

image.png

database1.gif

野菜入れにトマトを格納。
image.png
トマトの値を設定
追加でリンゴも設定
image.png
image.png

使用方法

using UnityEngine;

public class VegetableManager : MonoBehaviour
{
    public VegetableDatabase vegetableDatabase;

    void Start()
    {
        int searchId = 1; // 検索するIDを指定
        Vegetable foundVegetable = vegetableDatabase.GetVegetableById(searchId);

        if (foundVegetable != null)
        {
            Debug.Log("Vegetable Name: " + foundVegetable.vegetableName);
            Debug.Log("Price: " + foundVegetable.price);
        }
    }
}

空のオブジェクト作成
image.png
VegetableManagerをアタッチ
野菜入れも追加

image.png

実行結果
image.png

検索するidをもとにListを検索、出力できる。

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?