LoginSignup
11
11

More than 3 years have passed since last update.

あの日見たScriptableObjectの型を僕達はまだ知らない

Last updated at Posted at 2020-07-07

ScriptableObjectの読み込みを一元管理する

ScriptableObjectは便利ですよね。データをひとまとまりで取得できる優れものです。
今回はそれを読み込む流れを一元管理したいと思います。

読み込みが管理されていないと、どうなる?

Image2.png
クラスとScriptableObjectが「多対多」の関係になってしまい、人間の脳に優しくありません。

間に管理クラスを挟んで、「1対多」の関係を作る

Image1.png

管理クラス作成のために、ジェネリクスを使う

LoadData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public sealed class LoadData
{
    private static LoadData instance = new LoadData();

    public static LoadData Instance
    {
        get
        {
            return instance;
        }
    }
    // ScriptableObjectのみ受け付けるジェネリクスメソッド
    public T ScriptableLoader<T>(string path) where T : ScriptableObject
    {
        return Resources.Load<T>(path);
    }
}

こうすることで、ScriptableObjectが返されることを保証しつつ、様々な型のScriptableObjectを指定できます。

コード

今回使用したScrptableObjectです。

GameData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(menuName = "MyScript/Create GameData")]
public class GameData : ScriptableObject
{
    public int Data1;
    public string Data2;
    public float Data3;
}

これをもとに、ScriptableObjectを作成し、値を入れます。
Image4.png

それをStart()で表示してみます。

Game.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Game : MonoBehaviour
{

    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(LoadData.Instance.ScriptableLoader<GameData>("Data/MyGameData").Data1);
    }
}

実行結果

Image3.png

おわりに

以上、「ScriptableObjectの型は使いたいクラスだけが知っていればいいよね。読み込むクラスはそんなの知らなくていいよ」という話でした。

11
11
6

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
11
11