Unity-利用特性动态给脚本添加脚本

it2023-12-20  65

using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 指定特性运用与那一类型 /// 将对象指定为 class /// </summary> [AttributeUsage(AttributeTargets.Class)] public class BindPrefab : Attribute { //当前预制件路径 public string Path { get; private set; } public BindPrefab(string path) { Path = path; } } using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 将路径和 type类型进行存储 /// </summary> public class BindUtil { private static Dictionary<string, Type> _prefabAndScriptMap = new Dictionary<string, Type>(); /// <summary> /// 绑定路径以及 type 类型 /// </summary> /// <param name="path"></param> /// <param name="type"></param> public static void Bind(string path,Type type) { if (!_prefabAndScriptMap.ContainsKey(path)) { _prefabAndScriptMap.Add(path, type); } else { Debug.LogError("当前数据中存在路径:" + path); } } /// <summary> /// 获取Type 类型 /// </summary> /// <param name="path"></param> /// <returns></returns> public static Type GetType(string path) { //如果已经保存 if (_prefabAndScriptMap.ContainsKey(path)) { return _prefabAndScriptMap[path]; } else { Debug.LogError("当前数据中未包含路径" + path); return null; } } } using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; /// <summary> /// 对自己创建的特性初始化 /// </summary> public class InitCustomAttribute { public void Init() { //获取程序集 Assembly assembly = Assembly.GetAssembly(typeof(BindPrefab)); //获取程序集中的公有类型 //利用反射获取当前所有类型 Type[] types = assembly.GetExportedTypes(); //遍历获取特性 foreach (Type type in types) { //遍历类型所有特性 foreach (Attribute attribute in Attribute.GetCustomAttributes(type, true)) { if (attribute is BindPrefab) { BindPrefab data = attribute as BindPrefab; //保存绑定信息 BindUtil.Bind(data.Path, type); } } } } } 在这里插入代码片 using System.Collections; using System.Collections.Generic; using UnityEngine; [BindPrefab("Prefab/StartView")] public class StartView : MonoBehaviour { } //========================== // - FileName: GameRoot2.cs // - Created: #AuthorName# // - CreateTime: #CreateTime# // - Email: #AuthorEmail# // - Region: China WUHAN // - Description: //========================== using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test5 : MonoBehaviour { void Start() { InitCustomAttribute initCustomAttribute = new InitCustomAttribute(); initCustomAttribute.Init(); LoadPrefab("Prefab/StartView", transform); } public GameObject LoadPrefab(string path, Transform parent = null) { GameObject temp = LoadPrefabs(path, parent); Type type = BindUtil.GetType(path); temp.AddComponent(type); return temp; } public GameObject LoadPrefabs(string path, Transform parent = null) { GameObject prefab = Resources.Load<GameObject>(path); GameObject temp = UnityEngine.Object.Instantiate(prefab, parent); return temp; } }
最新回复(0)