GetField() public méthode

Searches for the public field with the specified name.
is null. This object is a whose method has not yet been called.
public GetField ( string name ) : FieldInfo
name string The string containing the name of the data field to get.
Résultat FieldInfo
        static DynamicScopeTokenResolver()
        {
            BindingFlags s_bfInternal = BindingFlags.NonPublic | BindingFlags.Instance;
            s_indexer = Type.GetType("System.Reflection.Emit.DynamicScope").GetProperty("Item", s_bfInternal);
            s_scopeFi = Type.GetType("System.Reflection.Emit.DynamicILGenerator").GetField("m_scope", s_bfInternal);

            s_varArgMethodType = Type.GetType("System.Reflection.Emit.VarArgMethod");
            s_varargFi1 = s_varArgMethodType.GetField("m_method", s_bfInternal);
            s_varargFi2 = s_varArgMethodType.GetField("m_signature", s_bfInternal);

            s_genMethodInfoType = Type.GetType("System.Reflection.Emit.GenericMethodInfo");
            s_genmethFi1 = s_genMethodInfoType.GetField("m_methodHandle", s_bfInternal);
            s_genmethFi2 = s_genMethodInfoType.GetField("m_context", s_bfInternal);

            s_genFieldInfoType = Type.GetType("System.Reflection.Emit.GenericFieldInfo", false);
            if (s_genFieldInfoType != null)
            {
                s_genfieldFi1 = s_genFieldInfoType.GetField("m_fieldHandle", s_bfInternal);
                s_genfieldFi2 = s_genFieldInfoType.GetField("m_context", s_bfInternal);
            }
            else
            {
                s_genfieldFi1 = s_genfieldFi2 = null;
            }
        }
			internal static void Initialize (Assembly KISasm)
			{
				ResourceInfo_class = KISasm.GetTypes().Where (t => t.Name.Equals ("ResourceInfo")).FirstOrDefault ();
				kis_resourceName = ResourceInfo_class.GetField ("resourceName");
				kis_maxAmount = ResourceInfo_class.GetField ("maxAmount");
				kis_amount = ResourceInfo_class.GetField ("amount");
			}
 public static bool HasField( Type objectType, string fieldName )
 {
     try
     {
         if ( String.IsNullOrEmpty( fieldName ) )
             return false;
         FieldInfo field = objectType.GetField( fieldName );
         if ( field == null )
             field = objectType.GetField( fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy );
         if ( field == null )
             field = objectType.BaseType.GetField( fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy );
         if ( field == null )
         {
             if ( ExtenderOptions.IsDebugging )
                 Log.Error( "Failed to find field '" + fieldName + "' in type '" + objectType.FullName + "'" );
             return false;
         }
         return true;
     }
     catch ( Exception ex )
     {
         if ( ExtenderOptions.IsDebugging )
             Log.Error( "Failed to find field '" + fieldName + "' in type '" + objectType.FullName + "': " + ex.Message );
         Log.Error( ex );
         return false;
     }
 }
Exemple #4
0
 static FGConsole()
 {
     consoleWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
     if (consoleWindowType != null)
     {
         consoleWindowField     = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
         consoleListViewField   = consoleWindowType.GetField("m_ListView", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         consoleActiveTextField = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         consoleOnGUIMethod     = consoleWindowType.GetMethod("OnGUI", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
     }
     listViewStateType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ListViewState");
     if (listViewStateType != null)
     {
         listViewStateRowField = listViewStateType.GetField("row", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     }
     editorWindowPosField = typeof(EditorWindow).GetField("m_Pos", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     logEntriesType       = typeof(EditorWindow).Assembly.GetType("UnityEditorInternal.LogEntries");
     if (logEntriesType != null)
     {
         getEntryMethod            = logEntriesType.GetMethod("GetEntryInternal", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
         startGettingEntriesMethod = logEntriesType.GetMethod("StartGettingEntries", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
         endGettingEntriesMethod   = logEntriesType.GetMethod("EndGettingEntries", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
     }
     logEntryType = typeof(EditorWindow).Assembly.GetType("UnityEditorInternal.LogEntry");
     if (logEntryType != null)
     {
         logEntry                = System.Activator.CreateInstance(logEntryType);
         logEntryFileField       = logEntryType.GetField("file", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         logEntryLineField       = logEntryType.GetField("line", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         logEntryInstanceIDField = logEntryType.GetField("instanceID", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     }
 }
        protected SandboxGameAssemblyWrapper()
        {
            m_instance = this;
            m_isDebugging = false;
            m_isUsingCommonProgramData = false;
            m_isInSafeMode = false;

            m_assembly = Assembly.UnsafeLoadFrom("Sandbox.Game.dll");

            m_mainGameType = m_assembly.GetType(MainGameNamespace + "." + MainGameClass);
            m_serverCoreType = m_assembly.GetType(ServerCoreClass);

            m_mainGameInstanceField = m_mainGameType.GetField(MainGameInstanceField, BindingFlags.Static | BindingFlags.Public);
            m_configContainerField = m_mainGameType.GetField(MainGameConfigContainerField, BindingFlags.Static | BindingFlags.Public);
            m_configContainerType = m_configContainerField.FieldType;
            m_serverCoreNullRender = m_serverCoreType.GetField(ServerCoreNullRenderField, BindingFlags.Public | BindingFlags.Static);

            m_configContainerDedicatedDataField = m_configContainerType.GetField(ConfigContainerDedicatedDataField, BindingFlags.NonPublic | BindingFlags.Instance);
            m_setConfigWorldName = m_configContainerType.GetMethod(ConfigContainerSetWorldName, BindingFlags.Public | BindingFlags.Instance);

            m_lastProfilingOutput = DateTime.Now;
            m_countQueuedActions = 0;
            m_averageQueuedActions = 0;

            Console.WriteLine("Finished loading SandboxGameAssemblyWrapper");
        }
        static DynamicScopeTokenResolver()
        {
            BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
            dynamicScopePropertyItem = Type.GetType("System.Reflection.Emit.DynamicScope").GetProperty("Item", flags);
            dynamicILGeneratorFieldScope = Type.GetType("System.Reflection.Emit.DynamicILGenerator").GetField("m_scope", flags);

            varArgMethodType = Type.GetType("System.Reflection.Emit.VarArgMethod");
            varArgMethodFieldMethod = varArgMethodType.GetField("m_method", flags);
            varArgMethodFieldSignature = varArgMethodType.GetField("m_signature", flags);

            genericMethodInfoType = Type.GetType("System.Reflection.Emit.GenericMethodInfo");
            genericMethodInfoFieldMethodHandle = genericMethodInfoType.GetField("m_method", flags); //use m_methodHandle in .Net 4.0
            if (genericMethodInfoFieldMethodHandle == null)
                genericMethodInfoFieldMethodHandle = genericMethodInfoType.GetField("m_methodHandle", flags);
            genericMethodInfoFieldContext = genericMethodInfoType.GetField("m_context", flags);

            genericFieldInfoType = Type.GetType("System.Reflection.Emit.GenericFieldInfo", false);
            if (genericFieldInfoType != null)
            {
                genericFieldInfoFieldFieldHandle = genericFieldInfoType.GetField("m_field", flags); //use m_fieldHandle in .Net 4.0
                if (genericFieldInfoFieldFieldHandle == null)
                    genericFieldInfoFieldFieldHandle = genericFieldInfoType.GetField("m_fieldHandle", flags);
                genericFieldInfoFieldContext = genericFieldInfoType.GetField("m_context", flags);
            }
            else
            {
                genericFieldInfoFieldFieldHandle = genericFieldInfoFieldContext = null;
            }
        }        
Exemple #7
0
 static FGConsole()
 {
     consoleWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
     if (consoleWindowType != null)
     {
         consoleWindowField = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
         consoleListViewField = consoleWindowType.GetField("m_ListView", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         consoleActiveTextField = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         consoleOnGUIMethod = consoleWindowType.GetMethod("OnGUI", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
     }
     listViewStateType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ListViewState");
     if (listViewStateType != null)
     {
         listViewStateRowField = listViewStateType.GetField("row", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     }
     editorWindowPosField = typeof(EditorWindow).GetField("m_Pos", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     logEntriesType = typeof(EditorWindow).Assembly.GetType("UnityEditorInternal.LogEntries");
     if (logEntriesType != null)
     {
         getEntryMethod = logEntriesType.GetMethod("GetEntryInternal", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
         startGettingEntriesMethod = logEntriesType.GetMethod("StartGettingEntries", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
         endGettingEntriesMethod = logEntriesType.GetMethod("EndGettingEntries", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
     }
     logEntryType = typeof(EditorWindow).Assembly.GetType("UnityEditorInternal.LogEntry");
     if (logEntryType != null)
     {
         logEntry = System.Activator.CreateInstance(logEntryType);
         logEntryFileField = logEntryType.GetField("file", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         logEntryLineField = logEntryType.GetField("line", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         logEntryInstanceIDField = logEntryType.GetField("instanceID", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     }
 }
Exemple #8
0
    public void ToggleGizmos(bool gizmosOn)
    {
        int      val = gizmosOn ? 1 : 0;
        Assembly asm = Assembly.GetAssembly(typeof(Editor));

        System.Type type = asm.GetType("UnityEditor.AnnotationUtility");
        if (type != null)
        {
            MethodInfo getAnnotations  = type.GetMethod("GetAnnotations", BindingFlags.Static | BindingFlags.NonPublic);
            MethodInfo setGizmoEnabled = type.GetMethod("SetGizmoEnabled", BindingFlags.Static | BindingFlags.NonPublic);
            MethodInfo setIconEnabled  = type.GetMethod("SetIconEnabled", BindingFlags.Static | BindingFlags.NonPublic);
            var        annotations     = getAnnotations.Invoke(null, null);
            foreach (object annotation in (IEnumerable)annotations)
            {
                System.Type annotationType   = annotation.GetType();
                FieldInfo   classIdField     = annotationType.GetField("classID", BindingFlags.Public | BindingFlags.Instance);
                FieldInfo   scriptClassField = annotationType.GetField("scriptClass", BindingFlags.Public | BindingFlags.Instance);
                if (classIdField != null && scriptClassField != null)
                {
                    int    classId     = (int)classIdField.GetValue(annotation);
                    string scriptClass = (string)scriptClassField.GetValue(annotation);
                    setGizmoEnabled.Invoke(null, new object[] { classId, scriptClass, val });
                    setIconEnabled.Invoke(null, new object[] { classId, scriptClass, val });
                }
            }
        }
    }
 private void Awake()
 {
     System.Type type = typeof(CanvasUpdateRegistry);
     FieldInfo field = type.GetField(nameof(m_LayoutRebuildQueue), BindingFlags.NonPublic | BindingFlags.Instance);
     m_LayoutRebuildQueue = (IList<ICanvasElement>)field.GetValue(CanvasUpdateRegistry.instance);
     field = type.GetField(nameof(m_GraphicRebuildQueue), BindingFlags.NonPublic | BindingFlags.Instance);
     m_GraphicRebuildQueue = (IList<ICanvasElement>)field.GetValue(CanvasUpdateRegistry.instance);
 }
			void InitializeField(Type type) {
				if (fieldInfo != null)
					return;

				var flags = SR.BindingFlags.Instance | SR.BindingFlags.Public | SR.BindingFlags.NonPublic;
				fieldInfo = type.GetField(fieldName1, flags);
				if (fieldInfo == null && fieldName2 != null)
					fieldInfo = type.GetField(fieldName2, flags);
			}
Exemple #11
0
        public void output_verification(Type output)
        {
            var expectedOutput = output.GetField("Output").GetValue(output) as string;
            var expectedExitCode = output.GetField("ExitCode").GetValue(output);

            var tag = output.Name.Replace("_output", "");
            var actualOutput = Run(tag);

            actualOutput.Item1.Is(expectedOutput.Replace("\r\n", "\n"));
            actualOutput.Item2.Is(expectedExitCode);
        }
Exemple #12
0
		public VisualControlInfo(string name, Type t)
		{
			Name = name;
			
			_GUID = Guid.Parse((string)t.GetField("GUID", BindingFlags.Static | BindingFlags.Public).GetValue(null));
			FieldInfo fi = t.GetField("ALLOW_MULTI", BindingFlags.Static | BindingFlags.Public);
			_allowMulti = fi != null ? (bool)fi.GetValue(false) : false;
			_version = (string)t.GetField("VERSION", BindingFlags.Static | BindingFlags.Public).GetValue(null);
			_dockStyle = (ControlDockStyle)t.GetField("DOCK_STYLE", BindingFlags.Static | BindingFlags.Public).GetValue(null);
			_classType = t;
			_instance_GUID = _GUID; // this is template info
		}
    static RtsBrushAssetRecordWrapper()
    {
        BindingFlags instanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

        _tyBrushAssetRecord             = Type.GetType("Rotorz.TileSystem.Editor.BrushAssetRecord,RotorzTileSystemEditor");
        _fiBrushAssetRecord_brush       = _tyBrushAssetRecord.GetField("brush", instanceBindingFlags);
        _fiBrushAssetRecord_displayName = _tyBrushAssetRecord.GetField("displayName", instanceBindingFlags);
        _piBrushAssetRecord_DisplayName = _tyBrushAssetRecord.GetProperty("DisplayName", instanceBindingFlags);
        _fiBrushAssetRecord_filePath    = _tyBrushAssetRecord.GetField("filePath", instanceBindingFlags);
        _piBrushAssetRecord_AssetPath   = _tyBrushAssetRecord.GetProperty("AssetPath", instanceBindingFlags);
        _fiBrushAssetRecord_master      = _tyBrushAssetRecord.GetField("master", instanceBindingFlags);
        _piBrushAssetRecord_IsMaster    = _tyBrushAssetRecord.GetProperty("IsMaster", instanceBindingFlags);
    }
    static NewScriptDefaultPathWindow()
    {
        var types = typeof(EditorWindow).Assembly.GetTypes();

        AddComponentWindowType = types.Where(t => t.Name == "AddComponentWindow").FirstOrDefault();
        s_AddComponentWindow   = AddComponentWindowType.GetField("s_AddComponentWindow", BindingFlags.NonPublic | BindingFlags.Static);
        m_Tree = AddComponentWindowType.GetField("m_Tree", BindingFlags.NonPublic | BindingFlags.Instance);
        var nestedTypes = AddComponentWindowType.GetNestedTypes(BindingFlags.NonPublic);

        NewScriptElement          = nestedTypes.Where(t => t.Name == "NewScriptElement").FirstOrDefault();
        m_Directory               = NewScriptElement.GetField("m_Directory", BindingFlags.NonPublic | BindingFlags.Instance);
        EditorApplication.update += BackgroundCheck;
    }
    // 1컬럼, 2컬럼, 씬에 상관 없이 마지막으로 클릭된 애셋이나 폴더의 경로를 리턴한다. 문제가 있으면 공백 리턴
    private string GetLastActivePath()
    {
        // http://blog.codestage.ru/2015/03/30/select-in-project-browser/ 프로젝트 브라우저 접근하는 방법 소개
        // https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ProjectBrowser.cs 프로젝트 브라우저 소스코드 (리플렉션으로 무엇을 가져올지 코드를 알면 편함)
        System.Type projectBrowserType         = System.Type.GetType("UnityEditor.ProjectBrowser,UnityEditor");
        FieldInfo   lastProjectBrowser         = projectBrowserType.GetField("s_LastInteractedProjectBrowser", BindingFlags.Static | BindingFlags.Public);
        object      lastProjectBrowserInstance = lastProjectBrowser.GetValue(null);

        FieldInfo projectBrowserViewMode = projectBrowserType.GetField("m_ViewMode", BindingFlags.Instance | BindingFlags.NonPublic);
        int       viewMode = (int)projectBrowserViewMode.GetValue(lastProjectBrowserInstance);

        string path = "";

        // Asset인 경우에만 경로 세팅
        // 0 - one column, 1 - two column
        if (viewMode == 1)
        {
            // Two column
            MethodInfo activeFolderPathInfo = projectBrowserType.GetMethod("GetActiveFolderPath", BindingFlags.NonPublic | BindingFlags.Instance);
            path = (string)activeFolderPathInfo.Invoke(lastProjectBrowserInstance, new object[] { });
        }
        else
        {
            // One column
            if (Selection.activeObject != null)
            {
                if (AssetDatabase.Contains(Selection.activeObject))
                {
                    // activeObject가 프로젝트에서 선택된 경우
                    path = AssetDatabase.GetAssetPath(Selection.activeObject);
                    if (Directory.Exists(path) == false)
                    {
                        // 폴더가 아닌 애셋이 선택된 경우 path에서 파일명을 없애야함
                        path = Path.GetDirectoryName(path);
                    }
                }
                else
                {
                    // activeObject가 씬에서 선택된 경우
                    return("");
                }
            }
            else
            {
                // null
                return("");
            }
        }

        return(path);
    }
Exemple #16
0
    ///<summary>тоглоом эхлэхэд GameView scale-г тааруулна</summary>
    public static void SetGameViewScale()
    {
#if UNITY_EDITOR
        System.Reflection.Assembly assembly = typeof(EditorWindow).Assembly;
        System.Type  type          = assembly.GetType("UnityEditor.GameView");
        EditorWindow v             = EditorWindow.GetWindow(type);
        var          defScaleField = type.GetField("m_defaultScale", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        float        defaultScale  = 0.1f;
        var          areaField     = type.GetField("m_ZoomArea", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        var          areaObj       = areaField.GetValue(v);
        var          scaleField    = areaObj.GetType().GetField("m_Scale", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        scaleField.SetValue(areaObj, new Vector2(defaultScale, defaultScale));
#endif
    }
Exemple #17
0
 public DocumentedEnum(Identifier name, XmlNode xml, MemberInfo mi, Type targetType)
 {
     Name = name;
     Xml = xml;
     Member = mi;
     TargetType = targetType;
     try
     {
         Value = (int)targetType.GetField(mi.Name).GetValue(null);
     }
     catch (Exception e)
     {
         Value = (uint)targetType.GetField(mi.Name).GetValue(null);
     }
 }
Exemple #18
0
        public static FieldInfo GetField(Type t, string name)
        {
            var type = t;
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
            FieldInfo finfo = null;
            while(t != null)
            {
                finfo = t.GetField(name, flags) ?? t.GetField(UnTitleCase(name), flags);
                if (finfo != null)
                    return finfo;

                t = t.BaseType;
            }
            return finfo;
        }
Exemple #19
0
    public void LoadData()
    {
        PlayerController.player.transform.position = new Vector3(PlayerPrefs.GetFloat("Player_Position_x"), PlayerPrefs.GetFloat("Player_Position_y"), PlayerPrefs.GetFloat("Player_Position_z"));

        string[]    ignore_fields = { "characterImage", "expToNextLevel", "bonusMP", "characterName" };
        System.Type playerType    = charStat.GetType().GetElementType();

        for (int i = 0; i < charStat.Length; i++)
        {
            if (PlayerPrefs.GetInt("Player_" + charStat[i].characterName + "_active") == 0)
            {
                charStat[i].gameObject.SetActive(false);
            }
            else
            {
                charStat[i].gameObject.SetActive(true);
            }

            //go through each player and save their stats
            foreach (var field in playerType.GetFields())
            {
                if (ignore_fields.Contains(field.Name))
                {
                    continue; //skip fields in ignore list
                }
                var    value     = playerType.GetField(field.Name).GetValue(charStat[i]);
                string pref_name = "Player_" + charStat[i].characterName + "_" + field.Name;

                if (value.GetType() == typeof(string))
                {
                    var fieldProperty = playerType.GetField(field.Name);
                    field.SetValue(charStat[i], PlayerPrefs.GetString(pref_name));
                }
                if (value.GetType() == typeof(int))
                {
                    var fieldProperty = playerType.GetField(field.Name);
                    field.SetValue(charStat[i], PlayerPrefs.GetInt(pref_name));
                }
            }
        }

        //get inventory data
        for (int i = 0; i < itemsHeld.Length; i++)
        {
            itemsHeld[i]     = PlayerPrefs.GetString("ItemInInventory_" + i);
            numberOfItems[i] = PlayerPrefs.GetInt("ItemAmount_" + i);
        }
    }
        /// <summary>
        /// Retrieves the field info matching the specified property path on the object given
        /// </summary>
        /// <typeparam name="T">The type of the object</typeparam>
        /// <param name="obj">The object to retrieve the property from</param>
        /// <param name="propertyPath">The path of the property</param>
        /// <param name="type">The Type object corresponding to the object's type</param>
        /// <returns>The property's info</returns>
        private GetSettable GetTargetProperty <T>(T obj, string propertyPath, System.Type type = null)
        {
            System.Type targetType = type ?? typeof(T);
            int         pointIndex = propertyPath.IndexOf(".");

            if (pointIndex != -1)
            {
                string       propertyName = propertyPath.Substring(0, pointIndex);
                GetSettable  property;
                FieldInfo    fieldInfo    = targetType.GetField(propertyName);
                PropertyInfo propertyInfo = targetType.GetProperty(propertyName);
                if (fieldInfo != null)
                {
                    property = new FieldWrapper(fieldInfo, obj);
                }
                else if (propertyInfo != null)
                {
                    property = new PropertyWrapper(propertyInfo, obj);
                }
                else
                {
                    Debug.Log("Property " + propertyName + " not found on object type " + type.ToString());
                    return(null);
                }
                var propertyObj = property.GetValue(obj);
                return(GetTargetProperty(propertyObj, propertyPath.Substring(pointIndex + 1), property.GetSettableType));
            }
            else
            {
                GetSettable  property;
                FieldInfo    fieldInfo    = targetType.GetField(propertyPath);
                PropertyInfo propertyInfo = targetType.GetProperty(propertyPath);
                if (fieldInfo != null)
                {
                    property = new FieldWrapper(fieldInfo, obj);
                }
                else if (propertyInfo != null)
                {
                    property = new PropertyWrapper(propertyInfo, obj);
                }
                else
                {
                    property = null;
                    Debug.Log("Property " + propertyPath + " not found on object type " + type.ToString());
                }
                return(property);
            }
        }
        public static FieldInfo GetField(Type type, string fieldName, bool throwIfInvalid)
        {
            if (string.IsNullOrEmpty(fieldName))
            {
                throw new ArgumentNullException("fieldName");
            }

            FieldInfo fieldInfo = type.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance);

            if (!IsValidField(fieldInfo))
            {
                if (throwIfInvalid)
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                              Resources.ExceptionInvalidField,
                                                              fieldName,
                                                              type.FullName));
                }

                return null;

            }

            return fieldInfo;
        }
Exemple #22
0
    public static T GetAttribute <T>(this System.Enum e) where T : System.Attribute
    {
        System.Type type      = e.GetType();
        FieldInfo   fieldInfo = type.GetField(System.Enum.GetName(type, e));

        return(fieldInfo.GetCustomAttribute <T>());
    }
    private static object GetValue(object source, string name)
    {
        if (source == null)
        {
            return(null);
        }

        System.Type type = source.GetType();

        while (type != null)
        {
            FieldInfo fieldInfo = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            if (fieldInfo != null)
            {
                return(fieldInfo.GetValue(source));
            }

            PropertyInfo propertyInfo = type.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (propertyInfo != null)
            {
                return(propertyInfo.GetValue(source, null));
            }

            type = type.BaseType;
        }
        return(null);
    }
    // 得到关卡解锁等级
    public int GetStageUnlockLevel(int stageId)
    {
        if (!DataManager.Scene_StageSceneTable.ContainsKey(stageId))
        {
            return(0);
        }

        System.Type type = typeof(Scene_StageSceneTableItem);
        Scene_StageSceneTableItem listRes = DataManager.Scene_StageSceneTable[stageId] as Scene_StageSceneTableItem;

        for (uint i = 0; i < Scene_StageSceneTableItem.MAX_UNLOCK_CONDITION_COUNT; ++i)
        {
            System.Reflection.FieldInfo fieldid = type.GetField("mUnlockCondId" + i.ToString());
            int unlockcondid = (int)fieldid.GetValue(listRes);
            if (unlockcondid < 0)
            {
                continue;
            }

            if (!DataManager.ConditionTable.ContainsKey(unlockcondid))
            {
                continue;
            }

            ConditionTableItem condRes = DataManager.ConditionTable[unlockcondid] as ConditionTableItem;
            if (condRes.mType == ConditionType.LEVEL)
            {
                return(condRes.mValue);
            }
        }

        return(0);
    }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 private IValueExtractor ScanForField(Type type)
 {
     FieldInfo fi = type.GetField(mPartName);
     if (fi != null)
         return new FieldInfoValueExtractor(fi);
     return null;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:DelegateFieldSetAccessor"/> class
        /// for field get access via DynamicMethod.
        /// </summary>
        /// <param name="targetObjectType">Type of the target object.</param>
        /// <param name="fieldName">Name of the field.</param>
        public DelegateFieldSetAccessor(Type targetObjectType, string fieldName)
        {
            // this.targetType = targetObjectType;
            _fieldName = fieldName;

            FieldInfo fieldInfo = targetObjectType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            // Make sure the field exists
            if (fieldInfo == null)
            {
                throw new NotSupportedException(
                    string.Format("Field \"{0}\" does not exist for type "
                    + "{1}.", fieldName, targetObjectType));
            }
            else
            {
                _fieldType = fieldInfo.FieldType;
                this.nullInternal = this.GetNullInternal(_fieldType);

                // Emit the IL for set access.
                DynamicMethod dynamicMethodSet = new DynamicMethod("SetImplementation", null, new Type[] { typeof(object), typeof(object) }, this.GetType().Module, false);
                ILGenerator ilgen = dynamicMethodSet.GetILGenerator();

                ilgen = dynamicMethodSet.GetILGenerator();

                ilgen.Emit(OpCodes.Ldarg_0);
                ilgen.Emit(OpCodes.Ldarg_1);
                UnboxIfNeeded(fieldInfo.FieldType, ilgen);
                ilgen.Emit(OpCodes.Stfld, fieldInfo);
                ilgen.Emit(OpCodes.Ret);

                _set = (SetValue)dynamicMethodSet.CreateDelegate(typeof(SetValue));
            }
        }
        public static void Enable(Type resourcesType)
        {
            if (null == resourcesType)
            {
                throw new ArgumentNullException("resourcesType");
            }

            // Get the ResourceManager property
            var resourceManagerProperty = resourcesType.GetProperty("ResourceManager", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
            if (null == resourceManagerProperty)
            {
                throw new NotSupportedException("RESX managed wrapper class does not contain the expected internal/public static ResourceManager property.");
            }

            // Get the ResourceManager value (ensures the resourceMan field gets initialized)
            var resourceManagerValue = resourceManagerProperty.GetValue(null, null) as ResourceManager;
            if (null == resourceManagerValue)
            {
                throw new NotSupportedException("RESX managed wrapper class returned null for the ResourceManager property getter.");
            }

            // Get the resourceMan field
            var resourceManField = resourcesType.GetField("resourceMan", BindingFlags.Static | BindingFlags.NonPublic);
            if (null == resourceManField)
            {
                throw new NotSupportedException("RESX managed wrapper class does not contain the expected private static resourceMan field.");
            }

            // Create a substitute ResourceManager to do the pseudo-localization
            var resourceManSubstitute = new PseudoLocalizerResourceManager(resourceManagerValue.BaseName, resourcesType.Assembly);

            // Replace the resourceMan field value
            resourceManField.SetValue(null, resourceManSubstitute);
        }
 private void FindInherited(Type type, LitTable table)
 {
     if (type.IsDefined(typeof(MapAttribute), false))
     {
         object[] attrs = type.GetCustomAttributes(typeof(MapAttribute), false);
         foreach (MapAttribute attr in attrs)
         {
             IDataBridge data = null;
             BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
             MemberInfo member = type.GetProperty(attr.Field, flags);
             if (member != null)
             {
                 data = new PropertyBridge((PropertyInfo)member);
             }
             else
             {
                 member = type.GetField(attr.Field, flags);
                 if (member != null)
                     data = new FieldBridge((FieldInfo)member);
                 else
                     throw new LightException("member " + attr.Field + " not found in class " + type.Name);
             }
             if (attr.Name == null || attr.Name.Length == 0)
                 attr.Name = member.Name;
             SqlColumn column = new SqlColumn(table, attr.Name, data);
             if (attr.Alias == null || attr.Alias.Length == 0)
                 column.Alias = attr.Field;
             else
                 column.Alias = attr.Alias;
             column.IsID = attr.ID;
             column.IsPK = attr.PK;
             table.Add(column);
         }
     }
 }
        public TimeSheetFieldMap(Type MQObjectType, string attributeName, string fieldName, bool hasDefault, bool isRequired)
        {
            _attributeName = attributeName;
            _fieldName = fieldName;
            _hasdefaultValue = hasDefault;
            _required = isRequired;

            _reflectionPermission.Demand();
            _reflectionPermission.Assert();
            try
            {
                _fieldInfo = MQObjectType.GetField(attributeName, BindingFlags.NonPublic | BindingFlags.Instance);
                if (null == _fieldInfo)
                {
                    throw new ApplicationException(string.Format("Couldn't access FieldInfo for {0} in {1}.", _attributeName, MQObjectType.Name));
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }

            if (_fieldInfo.FieldType.IsSubclassOf(typeof(TimeSheetBase)))
            {
                _referenceType = _fieldInfo.FieldType;
            }
            else if (_fieldInfo.FieldType.IsSubclassOf(typeof(System.Enum)))
            {
                _enumType = _fieldInfo.FieldType;
            }
        }
 public static FieldInfo FindFieldThroughoutHierarchy(Type type, string name)
 {
     FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
     if (field == null && type.GetCustomAttributes(_includeBaseAttributeType, false).Length > 0)
         field = FindFieldThroughoutHierarchy(type.BaseType, name);
     return field;
 }
Exemple #31
0
        /// <summary>
        /// make sure to Convert enum to Dictionary;
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static Dictionary<int, string> EnumToDictionary(Type enumType)
        {
            string keyName = enumType.FullName;

            if (!_EnumList.ContainsKey(keyName))
            {
                Dictionary<int, string> list = new Dictionary<int, string>();

                foreach (int i in Enum.GetValues(enumType))
                {
                    string name = Enum.GetName(enumType, i);
                    string label = name;
                    object[] atts = enumType.GetField(name).GetCustomAttributes(typeof(EnumLabelAttribute), false);
                    if (atts.Length > 0) label = ((EnumLabelAttribute)atts[0]).Label;

                    list.Add(i, label);
                }

                object obj = new object();

                if (!_EnumList.ContainsKey(keyName))
                {
                    lock (obj)
                    {
                        if (!_EnumList.ContainsKey(keyName))
                        {
                            _EnumList.Add(keyName, list);
                        }
                    }
                }
            }

            return _EnumList[keyName];
        }
 public override object Deserialize(Stream serializationStream, Type t)
 {
     var arrayField = t.BaseType.GetField("_data", BindingFlags.NonPublic | BindingFlags.Instance);
     var arrayType = arrayField.FieldType.GetElementType();
     var sizeType = (Type) t.GetField("SizeType").GetValue(null);
     var sizeFormatter = _typeFormatterFactory.GetFormatter(sizeType);
     var rawSize = sizeFormatter.Deserialize(serializationStream, sizeType);
     var arraySize = PrimitiveSupport.TypeToInt(rawSize);
     if (arrayType == typeof (Byte))
     {
         var arrayData = new byte[arraySize];
         serializationStream.Read(arrayData, 0, arraySize);
         var ret = t.GetConstructor(new Type[] {typeof (Byte[])}).Invoke(new object[] {arrayData});
         return ret;
     }
     else
     {
         var ret = t.GetConstructor(new Type[] {typeof (ulong)}).Invoke(new object[] {(ulong)arraySize});
         var array = (Array)arrayField.GetValue(ret);
         var subFormatter = _typeFormatterFactory.GetFormatter(arrayType);
         for (var i = 0; i < arraySize; i++)
         {
             array.SetValue(subFormatter.Deserialize(serializationStream, arrayType), i);
         }
         return ret;
     }
 }
Exemple #33
0
    public object GetValue(string valueName)
    {
        FieldInfo field = null;

        // Add MethodInfo to cache
        if (!decorateFields.ContainsKey(valueName))
        {
            var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;

            field = decoratedEditorType.GetField(valueName, flags);

            if (field != null)
            {
                decorateFields[valueName] = field;
            }
            else
            {
                Debug.LogError(string.Format("Could not find field {0}", valueName));
            }
        }
        else
        {
            field = decorateFields[valueName];
        }

        if (field != null)
        {
            return(field.GetValue(editorInstance));
        }
        return(null);
    }
Exemple #34
0
 public Type CreateType()
 {
     foreach (string name in instanceNames)
     {
         typeBuilder.DefineField(
             name,
             typeof(object),
             FieldAttributes.Public);
     }
     
     foreach (Method method in methods)
     {
         typeBuilder.DefineField(
             method.Name,
             typeof(Method),
             FieldAttributes.Public);
     }
     
     DefineParserConstructor();
     
     foreach (Method constructor in constructors)
         DefineConstructor(constructor);
     
     if (constructors.Count == 0)
         DefineDefaultConstructor();
     
     type = typeBuilder.CreateType();
     
     type.GetField("pattern").SetValue(null, pattern);
     
     pattern.SetType(type);
     
     return type;
 }
Exemple #35
0
 /// <summary>
 /// Gets the description for certaing named value in an Enumeration
 /// </summary>
 /// <param name="value">The type of the Enumeration</param>
 /// <param name="name">The name of the Enumeration value</param>
 /// <returns>The description, if any, else the passed name</returns>
 public static string GetEnumDescription(Type value, string name) {
     FieldInfo fi = value.GetField(name);
     var attributes =
         (DescriptionAttribute[])fi.GetCustomAttributes(
                                      typeof(DescriptionAttribute), false);
     return (attributes.Length > 0) ? attributes[0].Description : name;
 }
Exemple #36
0
    protected FieldInfo GetField(string fieldName)
    {
        FieldInfo field = null;

        // Add MethodInfo to cache
        if (!decoratedFields.ContainsKey(fieldName))
        {
            var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;

            field = decoratedEditorType.GetField(fieldName, flags);

            if (field != null)
            {
                decoratedFields[fieldName] = field;
            }
            else
            {
                Debug.LogError(string.Format("Could not find field {0}", field));
            }
        }
        else
        {
            field = decoratedFields[fieldName];
        }

        return(field);
    }
Exemple #37
0
 public static void SetPropertyValue(this SerializedProperty property, object value)
 {
     System.Type parentType         = property.serializedObject.targetObject.GetType();
     System.Reflection.FieldInfo fi = parentType.GetField(property.propertyPath);
     //this FieldInfo contains the type.
     fi.SetValue(property.serializedObject.targetObject, value);
 }
 /// <summary>
 /// Uses reflection to get the field value from an object.
 /// </summary>
 ///
 /// <param name="type">The instance type.</param>
 /// <param name="instance">The instance object.</param>
 /// <param name="fieldName">The field's name which is to be fetched.</param>
 ///
 /// <returns>The field value from the object.</returns>
 public static object GetInstanceField(Type type, object instance, string fieldName)
 {
     BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
         | BindingFlags.Static;
     FieldInfo field = type.GetField(fieldName, bindFlags);
     return field.GetValue(instance);
 }
        private static DbProviderServices CreateProviderInstance(Type providerType)
        {
            Debug.Assert(providerType != null, "providerType != null");
            Debug.Assert(
                typeof(DbProviderServices).IsAssignableFrom(providerType),
                "expected type derived from DbProviderServices");

            const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
            var instanceMember = providerType.GetProperty("Instance", bindingFlags)
                                 ?? (MemberInfo)providerType.GetField("Instance", bindingFlags);

            if (instanceMember == null)
            {
                throw new InvalidOperationException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources_VersioningFacade.EF6Providers_InstanceMissing,
                        providerType.AssemblyQualifiedName));
            }

            var providerInstance = GetInstanceValue(instanceMember) as DbProviderServices;
            if (providerInstance == null)
            {
                throw new InvalidOperationException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources_VersioningFacade.EF6Providers_NotDbProviderServices,
                        providerType.AssemblyQualifiedName));
            }

            return providerInstance;
        }
Exemple #40
0
        static SystemItemFactory()
        {
            atomicValueType = typeof(XmlAtomicValue);

             if (!CLR.IsMono) {
            xmlTypeField = atomicValueType.GetField("xmlType", BindingFlags.Instance | BindingFlags.NonPublic);
            clrTypeField = atomicValueType.GetField("clrType", BindingFlags.Instance | BindingFlags.NonPublic);
            objValField = atomicValueType.GetField("objVal", BindingFlags.Instance | BindingFlags.NonPublic);
            unionValField = atomicValueType.GetField("unionVal", BindingFlags.Instance | BindingFlags.NonPublic);
            boolValField = unionValField.FieldType.GetField("boolVal", BindingFlags.Instance | BindingFlags.Public);
            dtValField = unionValField.FieldType.GetField("dtVal", BindingFlags.Instance | BindingFlags.Public);
            dblValField = unionValField.FieldType.GetField("dblVal", BindingFlags.Instance | BindingFlags.Public);
            i32ValField = unionValField.FieldType.GetField("i32Val", BindingFlags.Instance | BindingFlags.Public);
            i64ValField = unionValField.FieldType.GetField("i64Val", BindingFlags.Instance | BindingFlags.Public);
             }
        }
Exemple #41
0
 public static string GetEnumDescription(Type type, Object value)
 {
     FieldInfo fi = type.GetField(Enum.GetName(type, value));
     DescriptionAttribute dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
     if (dna != null) return dna.Description;
     else return value.ToString();
 }
		/// <summary>
		/// Initializes a new instance of the ClassPropInfo class.
		/// </summary>
		/// <param name="type">The type to analyze.</param>
		/// <param name="propertyName">The name of the field.</param>
		/// <param name="getMethod">True to bind to a get method, false to bind to a set method.</param>
		public ClassPropInfo(Type type, string propertyName, bool getMethod = true)
		{
			Name = propertyName;

			// try to look up a field with the name
			FieldInfo = type.GetField(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
			if (FieldInfo != null)
			{
				MemberType = FieldInfo.FieldType;
			}
			else
			{
				// get the property
				PropertyInfo p = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);
				if (p == null)
					throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Field/Property {0} does not exist on type {1}", propertyName, type));

				// get the getter or setter
				if (getMethod)
					MethodInfo = (p.DeclaringType == type) ? p.GetGetMethod(true) : p.DeclaringType.GetProperty(p.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase).GetGetMethod(true);
				else
					MethodInfo = (p.DeclaringType == type) ? p.GetSetMethod(true) : p.DeclaringType.GetProperty(p.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase).GetSetMethod(true);

				MemberType = p.PropertyType;
			}
		}
Exemple #43
0
		static ZipTools()
		{
			try
			{
				var windowsBase = typeof (Package).Assembly;
				ZipArchive = windowsBase.GetType("MS.Internal.IO.Zip.ZipArchive");
				ZipArchive_OpenOnFile = ZipArchive.GetMethod("OpenOnFile", BindingFlags.NonPublic | BindingFlags.Static);
				ZipArchive_GetFiles = ZipArchive.GetMethod("GetFiles", BindingFlags.NonPublic | BindingFlags.Instance);
				ZipArchive_ZipIOBlockManager = ZipArchive.GetField("_blockManager", BindingFlags.NonPublic | BindingFlags.Instance);

				ZipFileInfo = windowsBase.GetType("MS.Internal.IO.Zip.ZipFileInfo");
				ZipFileInfo_GetStream = ZipFileInfo.GetMethod("GetStream", BindingFlags.NonPublic | BindingFlags.Instance);
				ZipFileInfo_Name = ZipFileInfo.GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
				ZipFileInfo_FolderFlag = ZipFileInfo.GetProperty("FolderFlag", BindingFlags.NonPublic | BindingFlags.Instance);

				ZipIOBlockManager = windowsBase.GetType("MS.Internal.IO.Zip.ZipIOBlockManager");
				ZipIOBlockManager_Encoding = ZipIOBlockManager.GetField("_encoding", BindingFlags.NonPublic | BindingFlags.Instance);

				Enabled = true;
			}
			catch
			{
				Enabled = false;
			}
		}
		static API()
		{
			var editorAssembly = typeof(EditorWindow).Assembly;
			containerWindowType = editorAssembly.GetType("UnityEditor.ContainerWindow");
			viewType = editorAssembly.GetType("UnityEditor.View");
			dockAreaType = editorAssembly.GetType("UnityEditor.DockArea");
			parentField = typeof(EditorWindow).GetField("m_Parent", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
			if (dockAreaType != null)
			{
				panesField = dockAreaType.GetField("m_Panes", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
				addTabMethod = dockAreaType.GetMethod("AddTab", new System.Type[] { typeof(EditorWindow) });
			}
			if (containerWindowType != null)
			{
				windowsField = containerWindowType.GetProperty("windows", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic);
				mainViewField = containerWindowType.GetProperty("mainView", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic);
			}
			if (viewType != null)
				allChildrenField = viewType.GetProperty("allChildren", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic);
				
			FieldInfo windowsReorderedField = typeof(EditorApplication).GetField("windowsReordered", BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
			windowsReordered = windowsReorderedField.GetValue(null) as EditorApplication.CallbackFunction;

			System.Type projectWindowUtilType = editorAssembly.GetType("UnityEditor.ProjectWindowUtil");
			if (projectWindowUtilType != null)
				createAssetMethod = projectWindowUtilType.GetMethod("CreateAsset", new System.Type[] { typeof(Object), typeof(string) });
		}
 private static void HandleSerializable(XmlWriter writer, Type propertyType, object value)
 {
     if (propertyType.IsGenericType &&
         propertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
     {
         var underlyingType = Nullable.GetUnderlyingType(propertyType);
         HandleSerializable(writer, underlyingType, value);
     }
     else if (propertyType == typeof (DateTime))
     {
         var valueString = ((DateTime)value).ToString("yyyy-MM-dd");
         writer.WriteValue(SecurityElement.Escape(valueString));
     }
     else if (propertyType.IsEnum)
     {
         var valueString = value.ToString();
         var field = propertyType.GetField(valueString);
         var enumAttributes = Attribute.GetCustomAttributes(field, typeof (XmlEnumAttribute), true);
         if (enumAttributes.Length != 0)
         {
             var enumAttribute = (XmlEnumAttribute) enumAttributes[0];
             var enumName = enumAttribute != null ? enumAttribute.Name : valueString;
             writer.WriteValue(SecurityElement.Escape(enumName));
         }
         else
         {
             writer.WriteValue(SecurityElement.Escape(valueString));
         }
     }
     else
     {
         writer.WriteValue(value);
     }
 }
    internal static void FindReferencesInScene(AkWwiseTreeViewItem item)
    {
        var reference = WwiseObjectReference.FindWwiseObject(item.objectType, item.objectGuid);
        var path      = UnityEditor.AssetDatabase.GetAssetPath(reference);

        if (path.IndexOf(' ') != -1)
        {
            path = '"' + path + '"';
        }

        if (path == string.Empty)
        {
            UnityEngine.Debug.Log($"No references to {item.displayName} in scene.");
            return;
        }

#if !UNITY_2019_1_OR_NEWER
        //drop "Assets" part of path
        path = string.Join("/", path.Split('/').Skip(1));
#endif

        var searchFilter = "ref:" + path;

        System.Type type = typeof(UnityEditor.SearchableEditorWindow);
        System.Reflection.FieldInfo info = type.GetField("searchableWindows",
                                                         System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
        var searchableWindows = info.GetValue(null) as List <UnityEditor.SearchableEditorWindow>;

        foreach (UnityEditor.SearchableEditorWindow sw in searchableWindows)
        {
            info = type.GetField("m_HierarchyType",
                                 System.Reflection.BindingFlags.NonPublic);
            if (sw.GetType().ToString() == "UnityEditor.SceneHierarchyWindow")
            {
                if (sw.GetType().ToString() == "UnityEditor.SceneHierarchyWindow")
                {
                    System.Reflection.MethodInfo setSearchFilter = typeof(UnityEditor.SearchableEditorWindow).GetMethod(
                        "SetSearchFilter", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    object[] parameters = new object[] { searchFilter, 0, false, false };

                    setSearchFilter.Invoke(sw, parameters);
                    sw.Repaint();
                }
            }
        }
    }
Exemple #47
0
    /// <summary>
    /// 获取点击Log的文本信息
    /// </summary>
    /// <returns></returns>
    private static string GetSelectedStackTrace()
    {
        Assembly editorWindowAssembly = typeof(EditorWindow).Assembly;

        if (editorWindowAssembly == null)
        {
            return(null);
        }

        System.Type consoleWindowType = editorWindowAssembly.GetType("UnityEditor.ConsoleWindow");
        if (consoleWindowType == null)
        {
            return(null);
        }

        FieldInfo consoleWindowFieldInfo =
            consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);

        if (consoleWindowFieldInfo == null)
        {
            return(null);
        }

        EditorWindow consoleWindow = consoleWindowFieldInfo.GetValue(null) as EditorWindow;

        if (consoleWindow == null)
        {
            return(null);
        }

        if (consoleWindow != EditorWindow.focusedWindow)
        {
            return(null);
        }

        FieldInfo activeTextFieldInfo =
            consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);

        if (activeTextFieldInfo == null)
        {
            return(null);
        }

        return((string)activeTextFieldInfo.GetValue(consoleWindow));
    }
Exemple #48
0
    private object GetDebugValue(SerializedProperty property)
    {
        object parent     = SerializedPropertyHelper.GetParent(property);
        Type   parentType = parent.GetType();

        FieldInfo targetField = parentType.GetField("_debugValue", BindingFlags.Instance | BindingFlags.NonPublic);

        return(targetField.GetValue(parent));
    }
    void SetGameViewScale()
    {
        System.Reflection.Assembly assembly = typeof(UnityEditor.EditorWindow).Assembly;
        System.Type type           = assembly.GetType("UnityEditor.GameView");
        UnityEditor.EditorWindow v = UnityEditor.EditorWindow.GetWindow(type);

        var defScaleField = type.GetField("m_defaultScale", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

        //whatever scale you want when you click on play
        float defaultScale = 0.1f;

        var areaField = type.GetField("m_ZoomArea", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        var areaObj   = areaField.GetValue(v);

        var scaleField = areaObj.GetType().GetField("m_Scale", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

        scaleField.SetValue(areaObj, new Vector2(defaultScale, defaultScale));
    }
    /// <summary>
    /// Copy tile data from v1.x tile system to v2.x tile system.
    /// </summary>
    /// <param name="v1">Old tile system.</param>
    /// <param name="v2">New tile system.</param>
    private static void CopyTileData(MonoBehaviour v1, TileSystem v2)
    {
        RtsUpgradedBrushMap map = RtsBrushUpgradeUtility.BrushMappings;

        FieldInfo fiFlagsV1 = (_tyTileData != null)
                        ? _tyTileData.GetField("_flags", BindingFlags.NonPublic | BindingFlags.Instance)
                        : null;
        FieldInfo fiFlagsV2 = typeof(TileData).GetField("_flags", BindingFlags.NonPublic | BindingFlags.Instance);

        TileData newTile = new TileData();

        int rows    = (int)_fiTileSystem_rows.GetValue(v1);
        int columns = (int)_fiTileSystem_columns.GetValue(v1);

        for (int row = 0; row < rows; ++row)
        {
            for (int column = 0; column < columns; ++column)
            {
                object oldTile = _miTileSystem_GetTile.Invoke(v1, new object[] { row, column });
                if (oldTile == null)
                {
                    continue;
                }

                if (fiFlagsV1 != null)
                {
                    fiFlagsV2.SetValue(newTile, fiFlagsV1.GetValue(oldTile));
                }

                // Prepare new tile from old tile.
                newTile.brush           = map.Lookup((Object)_fiTileData_brush.GetValue(oldTile));
                newTile.gameObject      = (GameObject)_fiTileData_gameObject.GetValue(oldTile);
                newTile.orientationMask = (byte)_fiTileData_orientationMask.GetValue(oldTile);
                newTile.variationIndex  = (byte)(int)_fiTileData_variationIndex.GetValue(oldTile);
                newTile.Empty           = false;

                v2.SetTileFrom(row, column, newTile);
                Chunk chunk = v2.GetChunkFromTileIndex(row, column);

                ForceRepaintForAtlasTiles(newTile, chunk);

                if (newTile.gameObject != null)
                {
                    // Transfer ownership of attached game object.
                    newTile.gameObject.transform.parent = chunk.transform;
                }
            }
        }

        // Some tiles might need to be refreshed!
        v2.RefreshAllTiles(
            RefreshFlags.PreservePaintedFlags
            | RefreshFlags.PreserveTransform
            | RefreshFlags.UpdateProcedural
            );
    }
Exemple #51
0
    // Returns: object reference to a "public static main" object of the same type as the class provided, if it exists within the class provided.
    public static object GetMainOfClass(System.Type targetClass)
    {
        FieldInfo mainField = targetClass.GetField("main", BindingFlags.Public | BindingFlags.Static);

        if (mainField != null && mainField.FieldType == targetClass && IsAccessible(mainField))
        {
            return(mainField.GetValue(null));
        }
        return(null);
    }
Exemple #52
0
    // ========================================================================== //

    /* public - [Do~Somthing] Function          */

    public AssetBundleBrowserWrapper()
    {
        _pBrowser     = AssetBundleBrowserMain.GetWindow <AssetBundleBrowserMain>();
        _pBrowserType = _pBrowser.GetType();

        _pField_BuildTab      = _pBrowserType.GetField("m_BuildTab", BindingFlags.NonPublic | BindingFlags.Instance);
        _pAssetBundleBuildTab = _pField_BuildTab.FieldType;

        _pMethod_Build = _pAssetBundleBuildTab.GetMethod("ExecuteBuild", BindingFlags.NonPublic | BindingFlags.Instance);
    }
Exemple #53
0
    public static string GetEnumDesc(System.Enum obj)
    {
        string objName = obj.ToString();

        System.Type t  = obj.GetType();
        FieldInfo   fi = t.GetField(objName);

        System.ComponentModel.DescriptionAttribute[] arrDesc = (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
        return(arrDesc != null && arrDesc.Length > 0 ? arrDesc[0].Description : "");
    }
Exemple #54
0
    static IMEAutoChanger()
    {
        System.Type textEditorType = typeof(TextEditor);
        s_TextEditorHasFocusField = textEditorType.GetField("m_HasFocus", BindingFlags.NonPublic | BindingFlags.Instance);

        System.Type editorGUIType = typeof(EditorGUI);
        s_ActiveEditorField = editorGUIType.GetField("activeEditor", BindingFlags.NonPublic | BindingFlags.Static);

        EditorApplication.update += Update;
    }
Exemple #55
0
 private void OpenFolderInBrowser(int instanceId)
 {
     System.Type projectBrowserType = System.Type.GetType("UnityEditor.ProjectBrowser,UnityEditor");
     if (null == projectBrowserType)
     {
         Debug.LogError("Can't find UnityEditor.ProjectBrowser type!");
     }
     else
     {
         FieldInfo projectBrowserField = projectBrowserType.GetField("s_LastInteractedProjectBrowser", BindingFlags.Static | BindingFlags.Public);
         if (null == projectBrowserField)
         {
             Debug.LogError("Can't find s_LastInteractedProjectBrowser field!");
         }
         else
         {
             FieldInfo browserViewMode = projectBrowserType.GetField("m_ViewMode", BindingFlags.Instance | BindingFlags.NonPublic);
             if (null == browserViewMode)
             {
                 Debug.LogError("Can't find m_ViewMode field!");
             }
             else
             {
                 object projectBrowserInst = projectBrowserField.GetValue(null);
                 // ViewMode value 0 is one column, 1 is two column mode
                 if (1 != (int)browserViewMode.GetValue(projectBrowserInst))
                 {
                     MethodInfo setTwoColumnMode = projectBrowserType.GetMethod("SetTwoColumns", BindingFlags.Instance | BindingFlags.NonPublic);
                     setTwoColumnMode.Invoke(projectBrowserInst, null);
                 }
                 MethodInfo showFolderFunc = projectBrowserType.GetMethod("ShowFolderContents", BindingFlags.Instance | BindingFlags.NonPublic);
                 if (null == showFolderFunc)
                 {
                     Debug.LogError("Can't find ShowFolderContents method!");
                 }
                 else
                 {
                     showFolderFunc.Invoke(projectBrowserInst, new object[] { instanceId, true });
                 }
             }
         }
     }
 }
Exemple #56
0
    // Attempt to locate the member as a field, and deal with it based on the given parameters
    // Returns: boolean indicating whether the command was handled here
    public static bool CallField(System.Type targetClass, string varName, string parameters)
    {
        // Attempt to find the field
        FieldInfo targetVar      = targetClass.GetField(varName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
        object    targetInstance = null;

        if (targetVar == null)
        {
            targetInstance = GetMainOfClass(targetClass);
            if (targetInstance != null)
            {
                targetVar = targetClass.GetField(varName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
            }
        }
        if (targetVar == null || !IsAccessible(targetVar))
        {
            return(false);
        }                                                                           // Fail: Couldn't find field, or it's marked inaccessible
        // If field is found, deal with it appropriately based on the parameters given
        if (parameters == null || parameters.Length < 1)
        {
            string output = GetFieldValue(targetInstance, targetVar);
            if (output == null)
            {
                return(false);
            }                        // Fail: Field is not of a supported type
            Echo(varName + " is " + output);
            return(true);            // Success: Value is printed when no parameters given
        }
        if (IsCheat(targetVar) && !cheats)
        {
            PrintCheatMessage(targetVar.Name);
        }
        else
        {
            if (!SetFieldValue(targetInstance, targetVar, parameters.SplitUnlessInContainer(' ', '\"')))
            {
                Echo("Invalid " + targetVar.FieldType.Name + ": " + parameters);
            }
        }
        return(true);        // Success: Whether or not the field could be set, the user is notified and the case is handled
    }
Exemple #57
0
 public override Object findItem(string key)
 {
     if (GetMember(key) is MemberInfo member)
     {
         MemberTypes type = member.MemberType;
         if (type == MemberTypes.Method)
         {
             return(new DotnetMethod(Target, key)
             {
                 Engine = Engine
             });
         }
         else if (type == MemberTypes.Field)
         {
             object data = Type.GetField(key).GetValue(Target);
             return(toScriptObject(Engine, data));
         }
     }
     return(base.findItem(key));
 }
Exemple #58
0
    /*
     * SetValue<T>
     * template function
     *
     * searches for a variable with the given name and alters it's value
     * the function will fail silently if the variable doesn't exist
     *
     * @param string variableName - the name of the variable in the class
     * @param T value - the new value to give the variable
     * @returns void
     */
    public static void SetValue <T>(string variableName, T value)
    {
        //get the type to access information about the singleton's contents
        System.Type type = typeof(Settings);

        //get the variable from the type object
        FieldInfo field = type.GetField(variableName);

        //set the value (pass in null to get the singleton's values)
        field.SetValue(null, value);
    }
Exemple #59
0
    public static string GetTooltip(System.Type ty, string fieldName)
    {
        TooltipAttribute[] attributes = ty.GetField(fieldName).GetCustomAttributes(typeof(TooltipAttribute), true) as TooltipAttribute[];
        string             s          = "";

        if (attributes.Length > 0)
        {
            s = attributes [0].tooltip;
        }
        return(s);
    }