csharp 反思和习惯[属性]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 反思和习惯[属性]相关的知识,希望对你有一定的参考价值。

using UnityEngine;
using UnityEditor;
using System.Reflection;
using System;

[CustomEditor(typeof(Node))]
class NodeCustomEditor : Editor
{
   private void OnEnable()
   {
       MonoBehaviour[] sceneActive = GameObject.FindObjectsOfType<MonoBehaviour>();

       foreach (MonoBehaviour mono in sceneActive)
       {
           Type monoType = mono.GetType();

           // Retreive the fields from the mono instance
           FieldInfo[] objectFields = monoType.GetFields(BindingFlags.Instance | BindingFlags.Public);

           // search all fields and find the attribute [Position]
           for (int i = 0; i < objectFields.Length; i++)
           {
               PositionAttribute attribute = Attribute.GetCustomAttribute(objectFields[i], typeof(PositionAttribute)) as PositionAttribute;

               // if we detect any attribute print out the data.
               if (attribute != null)
               {
                   Debug.Log(attribute.position.x); // The attribute position Y for that instance variable "1"
                   Debug.Log(attribute.position.y); // The attribute position X for that instance variable "0"
                   Debug.Log(mono.GetType()); // The type of the mono script "Node"
                   Debug.Log(objectFields[i].Name); // The name of the marked variable - "node"
               }
           }
       }
   }
}
using UnityEngine;

public class Node : MonoBehaviour
{
   [Position(1, 0)]
   public object node;
}
using UnityEngine;
using System;

[AttributeUsage(AttributeTargets.Field)]
public class PositionAttribute : Attribute
{
   public readonly Vector2 position;

   public PositionAttribute(int x, int y)
   {
       position.x = x;
       position.y = y;
   }
}

以上是关于csharp 反思和习惯[属性]的主要内容,如果未能解决你的问题,请参考以下文章

csharp 反思例子2

csharp 反思的例子

我有一个很好的思维习惯-反思

百天践行02反思 | 成功人士都有写日记的习惯

一个程序员的六年反思,我为什么选择快速开发

一个程序员的六年反思,我为什么选择快速开发