ãUnityãReflectionã使ã£ãæ å ±åéã軽éåããã¢ã¤ãã¢
ã©ã¤ãã©ãªãéçºãã¦ããä¸ã§ãæ¸ãå¿å°ãæ
ä¿ããããã«Reflectionã使ç¨ãããå ´é¢ãåºã¦ãã¾ãã
ä¾ãã°ç¹å®ã®ãã¼ãæ¼ãããæã«æå®ããé¢æ°ãå®è¡ããããããªã·ã§ã¼ãã«ãããã¼ã®ä»çµã¿ãå®è£
ããå ´åãAttributeã§ã·ã§ã¼ãã«ããã¢ã¯ã·ã§ã³ãæå®åºæ¥ãããã«ãªã£ã¦ããã¨ä¾¿å©ã§ãã
[Shortcut("ãã¡ã¤ã«ä¿å", KeyCode.LeftControl, KeyCode.S)] static void OnSave() { // ä¿åå¦ç }
ãã®ãããªä½ãã«ãããã¨ããå ´åãã©ã¤ãã©ãªã®åæåå¦çã§ä»¥ä¸ã®ãããªã³ã¼ããæ¸ãã¦ã·ã§ã¼ãã«ããã¢ã¯ã·ã§ã³ãåéãããã¨ã«ãªãã¾ãã
void CollectShortcutActions() { // ã¢ããªå ã®å ¨ã¦ã®ã¢ã»ã³ããªãåå¾ foreach(var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { // ãã¹ã¦ã®åãåå¾ foreach(var type in assembly.GetTypes()) { // åã®ä¸ããprivate static, public staticé¢æ°ãåå¾ foreach(var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { // [Shortcut]ãæå®ããã¦ããããå¤å® var attr = method.GetCustomAttributes<ShortcutAttribute>(); if (attr == null) continue; // ã·ã§ã¼ãã«ããã¢ã¯ã·ã§ã³ã®ç»é²å¦ç } } } }
è¦ãããã«éããã§ããã
Reflectionã使ã£ãå¦çã¯ãã¡ãããªã¼ãã¼ãããã®é«ããã®ã§ãããã¢ããªå
ã®å
¨ã¦ã®Assemblyã«å¯¾ãã¦å¦çãè¡ã£ã¦ãããããUnityã¨ã³ã¸ã³ã®æã¤ã¯ã©ã¹ç¾¤ããã®Attributeã使ã£ã¦ããªãAssemblyã«å¯¾ãã¦ãæ¤ç´¢å¦çãè¡ãããããªãã®å¦çæéãããã£ã¦ãã¾ã£ã¦ãã¾ãã
ä»åã¯ãã®å¦çããªãã¹ã軽ãããããã®ã¢ã¤ãã¢ãå
±æãã¾ãã
Attributeã®Assemblyãåãã
ã¾ãåãã«ãåéãããAttributeã¯ã©ã¹ãå¥Assemblyã¸åãåãã¾ãã
Unityã«ã¯Assembly Definition Assetã¨ããä»çµã¿ããããæå®ãããã©ã«ã以ä¸ã®ã³ã¼ããå¥ã®Assemblyã¸åãåãããã¨ãã§ãã¾ãã
Assembly Definition Assetã«ã¤ãã¦ã¯ãå
¬å¼ããã¥ã¢ã«ããã¡ãã®ãã¼ã¸ãåç
§ãã¦ãã ããã
対象ã®AssemblyããAttributeã®Assemblyã«ä¾åãã¦ãããã©ããããã§ãã¯ãã
å½ç¶ã§ãããAttributeã使ç¨ãã¦ããã¯ã©ã¹ãå«ã¾ããAssemblyã¯ãAttributeãå®ç¾©ãããAssemblyãåç
§ãã¦ãã¾ãã
ä¾ãã°ShortcutAttributeãåéãããã¨èããã¨ãã¯ãShortcutAttributeãå®ç¾©ããAssemblyãåç
§ãã¦ãããã®ã ããæ¤ç´¢ããã°ãããã¨ã«ãªãã¾ãã
C#ã§ã¯ãAssemblyãã©ã®Assemblyãåç
§ãã¦ããããåå¾ããAPIãç¨æããã¦ãã¾ãã
ããã使ã£ã¦ãã·ã§ã¼ãã«ããã¢ã¯ã·ã§ã³ã®åéå¦çã以ä¸ã®ããã«æ¸ãæãã¾ãã
void CollectShortcutActions() { foreach(var method in GetAllMethodWithAttribute<ShortcutAttribute>()) { // ã·ã§ã¼ãã«ããã¢ã¯ã·ã§ã³ã®ç»é²å¦ç } } IEnumerator<MethodInfo> GetAllMethodWithAttribute<T>() where T : System.Attribute { var targetAssemblyName = typeof(T).Assembly.GetName().FullName; foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { var referencedAssemblies = assembly.GetReferencedAssemblies(); var isTarget = assembly.GetName().FullName == targetAssemblyName; if (!isTarget) { for (int i = 0; i < referencedAssemblies.Length; i++) { var assemblyInfo = referencedAssemblies[i]; if (assemblyInfo.FullName == targetAssemblyName) { isTarget = true; break; } } } if (!isTarget) continue; foreach (var type in assembly.GetTypes()) { foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { var attr = method.GetCustomAttributes<T>(); if (attr == null) continue; yield return method; } } } }
ããã§ãUnityã¨ã³ã¸ã³ã®ã¯ã©ã¹ç¾¤ãé¢ä¿ã®ãªãAssemblyã¸ã®æ¤ç´¢ãç¡ããªã£ããã¨ã«ãããå®è¡é度ãå¤§å¹ ã«æ¹åãã¾ãã