1
3

More than 5 years have passed since last update.

クラス名から Prefab を類推して GameObject を Instantiate

Last updated at Posted at 2013-11-29

Unity でクラス名から Resources 配下の Prefab を特定して Instantiate するというトリッキー?なコトしたかったので、書いてみた。

前提

sample.cs
using UnityEngine;

namespace Hoge {
    public class Fuga : MonoBehavior {
        // 何か処理
    }
}

ってなクラスを Assets/Resources/Prefabs/Hoge/Fuga.prefab に Add Component してあるとする。

Instantiate 処理

instantiate.cs
using UnityEngine;
using System.Text.RegularExpressions;

class Instantiator {
    public static GameObject Instantiate<T>() where T : MonoBehavior {
        string path = Regex.Replace(typeof(T).FullName, "\\.", "/");
        return Resources.Load("Resources/Prefabs/" + path) as GameObject;
    }
}

ポイントは typeof(T)System.Type を取得して、 .FullName で完全修飾名を拾うトコ。
んで、 namespace デリミタ (ピリオド) をディレクトリセパレータ (面倒なのでスラッシュベタ書きw) に変換して、 Resources.Load() したげる感じ。
// 「いやいや、そんなの基本だろ」とか言わない。

呼び出し

GameObject go = Instantiator.Instantiate<Hoge.Fuga>();

って感じに呼び出してあげると、(ディレクトリ構造に気を付ければ) 楽に掛けるんじゃないかな。

1
3
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
1
3