はじめに
クラス名のstringからSystem.Typeを取得するクラスの作り方をよく忘れてしまうので、備忘録として記事にしてみました。
使用例
以下のようにして使用します。
使用例
System.Type classType = TypeGetter.GetType("Hoge");
ソースコード
TypeGetterの実装は以下の通り。
コードが若干汚いですが、ご容赦ください
TypeGetter.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
/// <summary>
/// タイプの取得を行う
/// </summary>
public static class TypeGetter
{
static private Dictionary<string, List<Type>> typeDict;
static MonoScript[] monoScripts;
/// <summary>
/// プロジェクト内に存在する全スクリプトファイル
/// </summary>
static MonoScript[] MonoScripts { get { return monoScripts ?? (monoScripts = Resources.FindObjectsOfTypeAll<MonoScript>().ToArray()); } }
/// <summary>
/// クラス名からタイプを取得する
/// </summary>
public static Type GetType(string className)
{
if (typeDict == null)
{
// Dictionary作成
typeDict = new Dictionary<string, List<Type>>();
foreach (var type in GetAllTypes())
{
if (!typeDict.ContainsKey(type.Name))
{
typeDict.Add(type.Name, new List<Type>());
}
typeDict[type.Name].Add(type);
}
}
if (typeDict.ContainsKey(className)) // クラスが存在
{
return typeDict[className][0];
}
else
{
// クラスが存在しない場合
return null;
}
}
/// <summary>
/// 全てのクラスタイプを取得
/// </summary>
private static IEnumerable<Type> GetAllTypes()
{
// Unity標準のクラスタイプ
var buitinTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(asm => asm.GetTypes())
.Where(type => type != null && !string.IsNullOrEmpty(type.Namespace))
.Where(type => type.Namespace.Contains("UnityEngine"));
// 自作のクラスタイプ
var myTypes = MonoScripts
.Where(script => script != null)
.Select(script => script.GetClass())
.Where(classType => classType != null)
.Where(classType => classType.Module.Name == "Assembly-CSharp.dll");
return buitinTypes.Concat(myTypes)
.Distinct();
}
}
使ってみる
手順1. 以下の2つのクラスを追加します
Hoge.cs
namespace Fuga
{
public class Hoge
{
}
}
TestTypeGetter.cs
using UnityEngine;
using UnityEditor;
public class TestTypeGetter
{
[MenuItem("Test/Type Get Hoge")]
static void Test()
{
System.Type classType = TypeGetter.GetType("Hoge");
Debug.Log(classType);
}
}
手順2. メニューを選んで実行します
手順3. 結果
System.Typeの取得ができていることが確認できます。