Unity--プリフォームをロードするときに、プロパティを使用してスクリプトをプリフォームにマウントします.
3372 ワード
プロパティクラスBindPreの定義
using System;
[AttributeUsage(AttributeTargets.Class)]//
public class BindPre : Attribute
{
public string Path { get; private set; }
public BindPre(string path)
{
Path = path;
}
}
スクリプトにプロパティを追加
using UnityEngine;
[BindPre("Prefabs/12Attribute/StartView")]
public class StartView : MonoBehaviour
{
}
パスとタイプをバインドするツールクラス
using System;
using System.Collections.Generic;
using UnityEngine;
public class BindUtil
{
private static Dictionary _prefabAndScriptMap = new Dictionary();
public static void Bind(string path, Type type)
{
if (!_prefabAndScriptMap.ContainsKey(path))
{
_prefabAndScriptMap.Add(path, type);
}
else
{
Debug.LogError(" :" + path);
}
}
public static Type GetType(string path)
{
if (_prefabAndScriptMap.ContainsKey(path))
{
return _prefabAndScriptMap[path];
}
else
{
Debug.LogError(" :" + path);
return null;
}
}
}
反射によるカスタムプロパティの初期化
using System;
using System.Reflection;
public class InitCustomAttributes
{
public void Init()
{
Assembly assembly = Assembly.GetAssembly(typeof(BindPre));
Type[] types = assembly.GetExportedTypes();
foreach (Type type in types)
{
foreach (Attribute attribute in Attribute.GetCustomAttributes(type, true))
{
if (attribute is BindPre)
{
BindPre data = attribute as BindPre;
BindUtil.Bind(data.Path, type);
}
}
}
}
}
//ロードされたインタフェース
using UnityEngine;
public interface ILoader
{
GameObject LoadPrefab(string path, Transform parent = null);
}
ResourcesプリフォームをロードしILoaderのインタフェースを実現
using UnityEngine;
public class ResourcesLoader : ILoader
{
public GameObject LoadPrefab(string path, Transform parent = null)
{
GameObject prefab = Resources.Load(path);
GameObject temp = Object.Instantiate(prefab, parent);
return temp;
}
}
管理クラスのロード、プリミティブのロード、およびプリミティブをバインドするスクリプトの追加
using System;
using UnityEngine;
public class LoadMgr : Singleton
{
private ILoader _loader;
public LoadMgr()
{
_loader = new ResourcesLoader();
}
public GameObject LoadPrefab(string path, Transform parent = null)
{
GameObject temp = _loader.LoadPrefab(path, parent);
//Type type = Type.GetType(temp.name.Remove(temp.name.Length - 7));
Type type = BindUtil.GetType(path);
temp.AddComponent(type);
return temp;
}
}
ゲーム開始時の最初のスクリプト、初期化用
using UnityEngine;
public class LaunchGame : MonoBehaviour
{
void Awake()
{
InitCustomAttributes initAtt = new InitCustomAttributes();
initAtt.Init();
LoadMgr.Instance.LoadPrefab("Prefabs/12Attribute/StartView", transform);
}
}