当前位置: 首页>>代码示例>>C#>>正文


C# FieldInfo.SetValue方法代码示例

本文整理汇总了C#中FieldInfo.SetValue方法的典型用法代码示例。如果您正苦于以下问题:C# FieldInfo.SetValue方法的具体用法?C# FieldInfo.SetValue怎么用?C# FieldInfo.SetValue使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在FieldInfo的用法示例。


在下文中一共展示了FieldInfo.SetValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddField

 protected void AddField(FieldInfo field)
 {
     if (field.FieldType == typeof (int))
     {
         field.SetValue(target, EditorGUILayout.IntField(Clean(field.Name), (int) field.GetValue(target)));
     }
     else if (typeof (Object).IsAssignableFrom(field.FieldType))
     {
         field.SetValue(target,
             EditorGUILayout.ObjectField(Clean(field.Name), (Object) field.GetValue(target), field.FieldType, true));
     }
 }
开发者ID:pandarrr,项目名称:unity_tools,代码行数:12,代码来源:AutoBehaviourEditor.cs

示例2: Bind

	public void Bind(AudioSourcePro sourcePro)
	{
		if(isBound || isStandardEvent || sourceComponent == null)
			return;
		
		owner = sourcePro;

		if(!componentIsValid)
		{
			Debug.LogError(string.Format( "Invalid binding configuration - Source:{0}", sourceComponent));
			return;
		}
		
		MethodInfo eventHandlerMethodInfo = getMethodInfoForAction(actionType);
		
		targetComponent = owner;
		
		eventField = getField(sourceComponent, methodName);
		if(eventField == null)
		{
			Debug.LogError( "Event definition not found: " + sourceComponent.GetType().Name + "." + methodName );
			return;
		}
		
		try
		{
			var eventMethod = eventField.FieldType.GetMethod("Invoke");
			var eventParams = eventMethod.GetParameters();
			
			eventDelegate = createProxyEventDelegate(targetComponent, eventField.FieldType, eventParams, eventHandlerMethodInfo);
		}
		catch(Exception err)
		{
			Debug.LogError("Event binding failed - Failed to create event handler: " + err.ToString());
			return;
		}
		
		var combinedDelegate = Delegate.Combine( eventDelegate, (Delegate)eventField.GetValue( sourceComponent ) );
		eventField.SetValue( sourceComponent, combinedDelegate );
		
		isBound = true;
	}
开发者ID:pcobas,项目名称:pikieki,代码行数:42,代码来源:AudioSubscription.cs

示例3: setNewFieldValue

	void setNewFieldValue (FieldInfo fieldInfo, Component component, ref Dictionary<string, UFTAtlasEntryMetadata> targetAtlasByMetaDictionary)
	{
		if ( fieldInfo.FieldType == typeof(UFTAtlasMetadata)){
			fieldInfo.SetValue(component,atlasMetadataTo);
			//result=((UFTAtlasMetadata)fieldInfo.GetValue(go)).atlasName;	
		} else if ( fieldInfo.FieldType == typeof(UFTAtlasEntryMetadata)){
			UFTAtlasEntryMetadata oldEntryMeta= (UFTAtlasEntryMetadata)fieldInfo.GetValue(component);			
			string path=oldEntryMeta.assetPath;
			fieldInfo.SetValue(component,targetAtlasByMetaDictionary[path]);
		} else {
			throw new System.Exception("unsuported FieldInfo type exception  fieldType="+fieldInfo.FieldType);	
		}		
	}
开发者ID:nicloay,项目名称:unity3d-atlasEditor,代码行数:13,代码来源:UFTAtlasMigrateWindow.cs

示例4: DrawProperty

    protected virtual void DrawProperty(GUIContent label, FieldInfo field)
    {
        var fieldValue = field.GetValue (target);

        if (field.FieldType.IsArray) {
            var objArray = (object[])fieldValue;
            var elementType = field.FieldType.GetElementType ();

            // initialize array fields with empty arrays.
            if (objArray == null) {
                objArray = (object[])Array.CreateInstance (elementType, 0);
                field.SetValue (target, objArray);
                EditorUtility.SetDirty (target);
            }

            EditorGUILayout.BeginHorizontal ();
            GUIContent arrayInfo = new GUIContent (objArray.Length + (objArray.Length == 1 ? " item" : " items"));
            EditorGUILayout.LabelField (label, arrayInfo, UTEditorResources.ArrayLabelStyle);
            if (GUILayout.Button ("Add", UTEditorResources.ExpressionButtonStyle)) {
                var newArray = (object[])Array.CreateInstance (elementType, objArray.Length + 1);
                Array.Copy (objArray, newArray, objArray.Length);
                if (elementType.IsSubclassOf (typeof(UTPropertyBase))) {
                    newArray [newArray.Length - 1] = Activator.CreateInstance (elementType);
                }
                field.SetValue (target, newArray);
                GUI.changed = true;
                objArray = newArray;
            }

            EditorGUILayout.EndHorizontal ();

            EditorGUILayout.BeginVertical ();

            // the index of the element that should be deleted.
            // since the user cannot click multiple buttons at once
            // a single int is enough here.
            int deleteIndex = -1;
            for (int i = 0; i < objArray.Length; i++) {
                if (elementType.IsSubclassOf (typeof(UTPropertyBase))) {
                    propertyFieldWrapper.SetUp (emptyLabel, field, (UTPropertyBase)objArray [i]);
                    if (DrawPropertyArrayMember (propertyFieldWrapper)) {
                        deleteIndex = i;
                    }
                } else {
                    arrayMemberWrapper.SetUp (emptyLabel, field, objArray, i);
                    if (DrawPropertyArrayMember (arrayMemberWrapper)) {
                        deleteIndex = i;
                    }
                }
            }

            if (deleteIndex != -1) {
                var newArray = (object[])Array.CreateInstance (elementType, objArray.Length - 1);
                // no copy before index if the index was first element
                if (deleteIndex > 0) {
                    Array.Copy (objArray, 0, newArray, 0, deleteIndex);
                }
                // no copy after index if the index was last element
                if (deleteIndex + 1 < objArray.Length) {
                    Array.Copy (objArray, deleteIndex + 1, newArray, deleteIndex, objArray.Length - deleteIndex - 1);
                }
                field.SetValue (target, newArray);
                GUI.changed = true;
            }

            // add space only if array isn't empty, looks weird otherwise.
            if (objArray.Length > 0) {
                EditorGUILayout.Space ();
            }
            else {
                var hint = UTInspectorHint.GetFor(field);
                if (hint.arrayNotEmpty) {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel (" ");
                    EditorGUILayout.HelpBox ("At least one element is required.", MessageType.Error);
                    EditorGUILayout.EndHorizontal();
                }
            }

            EditorGUILayout.EndVertical ();

        } else {
            EditorGUILayout.BeginHorizontal ();
            if (field.FieldType.IsSubclassOf (typeof(UTPropertyBase))) {
                if (fieldValue == null) {
                    fieldValue = Activator.CreateInstance (field.FieldType); // make an empty instance
                    field.SetValue (target, fieldValue);
                    EditorUtility.SetDirty (target);
                }
                propertyFieldWrapper.SetUp (label, field, (UTPropertyBase)fieldValue);
                DrawProperty (propertyFieldWrapper, false);
            } else {
                plainFieldWrapper.SetUp (label, field, target);
                DrawProperty (plainFieldWrapper, false);
            }
            EditorGUILayout.EndHorizontal ();

        }
    }
开发者ID:realshyfox,项目名称:PlayMakerCustomActions_U3,代码行数:99,代码来源:UTInspectorRenderer.cs

示例5: OnSceneGUI

    internal void OnSceneGUI( EditableCurvableGeometry geometry )
    {
        this.geometry = geometry;

        // 		switch ( e.type )
        // 		{
        // 			case EventType.Layout:
        // 			case EventType.Repaint:
        // 			case EventType.MouseMove:
        // 				break;
        // 			default:
        // 				Debug.Log ( "e:" + e.type.ToString () );
        // 				break;
        // 		}

        bool doubleClick = false;
        if ( e.type == EventType.MouseDown && !e.control && !e.alt && !e.shift )
        {
            doubleClick = ( Time.realtimeSinceStartup - clickTime < doubleClickInterval );
            if ( doubleClick )
                clickTime = 0;
            else
                clickTime = Time.realtimeSinceStartup;
        }

        if ( geometry == null )
        {
            return;
        }

        if ( doubleClick )
        {
            SwitchEditionMode ();
            return;
        }

        if ( KeyPressed ( editKey ) || KeyPressed ( editKeyAlt ) )
            SwitchEditionMode ();

        if ( editing )
        {
            // 			if ( polyMesh != null )
            // 			{
            // 				Handles.BeginGUI ();
            // 				{
            // 					Vector3 screenPos = Camera.current.WorldToScreenPoint ( polyMesh.transform.position );
            // 					// GUI.Label ( new Rect ( screenPos.x, Screen.height - screenPos.y, 100, 20 ), "This is a label" );
            // 					EditorGUI.ColorField ( new Rect ( screenPos.x, Screen.height - screenPos.y, 100, 20 ), Color.white );
            // 				}
            // 				Handles.EndGUI ();
            // 			}

            //Update lists
            if ( keyPoints == null )
            {
                keyPoints = new List<Vector3> ( geometry.KeyPoints );
                curvePoints = new List<Vector3> ( geometry.CurvePoints );
                isCurve = new List<bool> ( geometry.IsCurve );
            }

            //Crazy hack to register undo
            if ( undoCallback == null )
            {
                undoCallback = typeof ( EditorApplication ).GetField ( "undoRedoPerformed", BindingFlags.NonPublic | BindingFlags.Static );
                if ( undoCallback != null )
                    undoCallback.SetValue ( null, new EditorApplication.CallbackFunction ( OnUndoRedo ) );
            }

            //Load handle matrix
            // 			Matrix4x4 cachedMatrix = Handles.matrix;
            Handles.matrix = geometry.Transform.localToWorldMatrix;

            //Draw points and lines
            DrawAxis ();
            Handles.color = Color.white;
            for ( int i = 0; i < keyPoints.Count; i++ )
            {
                Handles.color = nearestLine == i ? Color.green : Color.white;

                DrawSegment ( i );
                if ( selectedIndices.Contains ( i ) )
                {
                    Handles.color = Color.green;
                    DrawCircle ( keyPoints[i], 0.08f );
                }
                else
                    Handles.color = Color.white;
                DrawKeyPoint ( i );
                if ( isCurve[i] )
                {
                    Handles.color = ( draggingCurve && dragIndex == i ) ? Color.white : Color.blue;
                    DrawCurvePoint ( i );
                }
            }

            //			Handles.matrix = cachedMatrix;

            //Quit on tool change
            if ( e.type == EventType.KeyDown )
            {
//.........这里部分代码省略.........
开发者ID:apautrot,项目名称:gdp9,代码行数:101,代码来源:PolyMeshEditor.cs

示例6: BindListField

 /// <summary>
 /// Initializes the specified field of component to all instances of some type, given then information in bindAttribute.
 /// </summary>
 /// <param name="field">Field to bind</param>
 /// <param name="bindAttribute">Information about how to bind it</param>
 /// <param name="component">Object with the field</param>
 /// <param name="elementType">Element type of the field to be bound</param>
 // ReSharper disable UnusedParameter.Local
 private static void BindListField(FieldInfo field, BindAttribute bindAttribute, MonoBehaviour component, Type elementType)
 // ReSharper restore UnusedParameter.Local
 {
     System.Diagnostics.Debug.Assert(bindAttribute.Scope == BindingScope.Global);
     field.SetValue(component, Registry(elementType));
 }
开发者ID:tzamora,项目名称:superteam,代码行数:14,代码来源:BindingBehaviour.cs

示例7: BindSimpleField

    /// <summary>
    /// Initializes the specified field of component given then information in bindAttribute.
    /// </summary>
    /// <param name="field">Field to bind</param>
    /// <param name="bindAttribute">Information about how to bind it</param>
    /// <param name="component">Object with the field</param>
    private static void BindSimpleField(FieldInfo field, BindAttribute bindAttribute, MonoBehaviour component)
    {
        Object target = null;
        switch (bindAttribute.Scope)
        {
            case BindingScope.GameObject:
                target = component.GetComponent(field.FieldType);
                break;

            case BindingScope.GameObjectOrChildren:
                target = component.GetComponentInChildren(field.FieldType);
                break;

            case BindingScope.Global:
                target = FindObjectOfType(field.FieldType);
                break;
        }

        if (target == null)
            switch (bindAttribute.IfNotFound)
            {
                case BindingDefault.Exception:
                    throw new Exception("No target to bind to");

                case BindingDefault.Create:
                    target = component.gameObject.AddComponent(field.FieldType);
                    break;

                case BindingDefault.Ignore:
                    break;
            }

        field.SetValue(component, target);
    }
开发者ID:tzamora,项目名称:superteam,代码行数:40,代码来源:BindingBehaviour.cs

示例8: OnSceneGUI

	void OnSceneGUI()
	{
		if (target == null)
			return;

		if (KeyPressed(editKey))
			editing = !editing;

		if (editing)
		{
			//Update lists
			if (keyPoints == null)
			{
				keyPoints = new List<Vector3>(polyMesh.keyPoints);
				curvePoints = new List<Vector3>(polyMesh.curvePoints);
				isCurve = new List<bool>(polyMesh.isCurve);
			}

			//Crazy hack to register undo
			if (undoCallback == null)
			{
				undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", BindingFlags.NonPublic | BindingFlags.Static);
				if (undoCallback != null)
					undoCallback.SetValue(null, new EditorApplication.CallbackFunction(OnUndoRedo));
			}

			//Load handle matrix
			Handles.matrix = polyMesh.transform.localToWorldMatrix;

			//Draw points and lines
			DrawAxis();
			Handles.color = Color.white;
			for (int i = 0; i < keyPoints.Count; i++)
			{
				Handles.color = nearestLine == i ? Color.green : Color.white;
				DrawSegment(i);
				if (selectedIndices.Contains(i))
				{
					Handles.color = Color.green;
					DrawCircle(keyPoints[i], 0.08f);
				}
				else
					Handles.color = Color.white;
				DrawKeyPoint(i);
				if (isCurve[i])
				{
					Handles.color = (draggingCurve && dragIndex == i) ? Color.white : Color.blue;
					DrawCurvePoint(i);
				}
			}

			//Quit on tool change
			if (e.type == EventType.KeyDown)
			{
				switch (e.keyCode)
				{
				case KeyCode.Q:
				case KeyCode.W:
				case KeyCode.E:
				case KeyCode.R:
					return;
				}
			}

			//Quit if panning or no camera exists
			if (Tools.current == Tool.View || (e.isMouse && e.button > 0) || Camera.current == null || e.type == EventType.ScrollWheel)
				return;

			//Quit if laying out
			if (e.type == EventType.Layout)
			{
				HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
				return;
			}

			//Cursor rectangle
			EditorGUIUtility.AddCursorRect(new Rect(0, 0, Camera.current.pixelWidth, Camera.current.pixelHeight), mouseCursor);
			mouseCursor = MouseCursor.Arrow;

			//Extrude key state
			if (e.keyCode == extrudeKey)
			{
				if (extrudeKeyDown)
				{
					if (e.type == EventType.KeyUp)
						extrudeKeyDown = false;
				}
				else if (e.type == EventType.KeyDown)
					extrudeKeyDown = true;
			}

			//Update matrices and snap
			worldToLocal = polyMesh.transform.worldToLocalMatrix;
			inverseRotation = Quaternion.Inverse(polyMesh.transform.rotation) * Camera.current.transform.rotation;
			snap = gridSnap;
			
			//Update mouse position
			screenMousePosition = new Vector3(e.mousePosition.x, Camera.current.pixelHeight - e.mousePosition.y);
			var plane = new Plane(-polyMesh.transform.forward, polyMesh.transform.position);
			var ray = Camera.current.ScreenPointToRay(screenMousePosition);
//.........这里部分代码省略.........
开发者ID:CaminhoneiroHell,项目名称:PolyMesh,代码行数:101,代码来源:PolyMeshEditor.cs

示例9: SetField


//.........这里部分代码省略.........
            Color colorVal = Color.white;

            try
            {
                string[] splitColor = rawValue.Split(',');
                if (splitColor.Length == 3)
                    colorVal = new Color(float.Parse(splitColor[0].Trim()), float.Parse(splitColor[1].Trim()), float.Parse(splitColor[2].Trim()));
                else if (splitColor.Length == 4)
                    colorVal = new Color(float.Parse(splitColor[0].Trim()), float.Parse(splitColor[1].Trim()), float.Parse(splitColor[2].Trim()), float.Parse(splitColor[3].Trim()));
            }
            catch
            {
            }

            newVal = colorVal;
        }
        else if (field.FieldType == typeof (Vector2))
        {
            Vector2 vector = Vector2.zero;

            try
            {
                string[] splitVec = rawValue.Split(',');
                vector = new Vector2(float.Parse(splitVec[0].Trim()), float.Parse(splitVec[1].Trim()));
            }
            catch
            {
            }

            newVal = vector;
        }
        else if (field.FieldType == typeof (Vector3))
        {
            Vector3 vector = Vector3.zero;

            try
            {
                string[] splitVec = rawValue.Split(',');
                vector = new Vector3(float.Parse(splitVec[0].Trim()), float.Parse(splitVec[1].Trim()), float.Parse(splitVec[2].Trim()));
            }
            catch
            {
            }

            newVal = vector;
        }
        else if (field.FieldType == typeof (Vector4))
        {
            Vector4 vector = Vector4.zero;

            try
            {
                string[] splitVec = rawValue.Split(',');
                vector = new Vector4(float.Parse(splitVec[0].Trim()), float.Parse(splitVec[1].Trim()), float.Parse(splitVec[2].Trim()), float.Parse(splitVec[3].Trim()));
            }
            catch
            {
            }

            newVal = vector;
        }
        else if (field.FieldType.IsSubclassOf(typeof (Object)))
        {
            string[] matchingAssets = AssetDatabase.FindAssets(rawValue + " t:" + field.FieldType.Name);

            if (!matchingAssets.Any())
            {
                Debug.LogWarning("Unable to find object: " + rawValue + " for " + field.Name + " on datablock " + datablock.name);
                return;
            }

            Object obj = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(matchingAssets[0]), field.FieldType);
            newVal = obj;
        }
        else if (field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof (DatablockRef<>))
        {
            Object obj = Resources.Load(rawValue);
            if (!obj)
            {
                Debug.LogWarning("Unable to load resource: " + rawValue + " for " + field.Name + " on datablock " + datablock.name);
                return;
            }

            newVal = Activator.CreateInstance(field.FieldType, new object[] {obj});
        }
        else if (field.FieldType.IsEnum)
        {
            try
            {
                newVal = Enum.Parse(field.FieldType, rawValue);
            }
            catch (Exception)
            {
                Debug.LogError("Invalid enum vlue " + rawValue + " for " + field.Name + " on datablock " + datablock.name);
            }
        }

        field.SetValue(datablock, newVal);
        datablock.SetOverridesParent(field, true);
    }
开发者ID:Daloupe,项目名称:Syzygy_Git,代码行数:101,代码来源:DatablockImporter.cs

示例10: SetFieldToLocalMethod

	/// <summary>
	/// clears the invocation list of 'field', setting it to the
	/// local method
	/// </summary>
	protected void SetFieldToLocalMethod(FieldInfo field, MethodInfo method, Type type)
	{

		if (method == null)
		    return;

		Delegate assignment = Delegate.CreateDelegate(type, method);

		if (assignment == null)
		{
			Debug.LogError("Error (" + this + ") Failed to bind: " + method + ".");
			return;
		}

		field.SetValue(this, assignment);

	}
开发者ID:loursbrun,项目名称:sniperspiritV3,代码行数:21,代码来源:vp_Event.cs

示例11: OnInspectorGUI

	public override void OnInspectorGUI()
	{
		//Get tilemap
		if (tileMap == null)
			tileMap = (TileMap)target;

		//Crazy hack to register undo
		if (undoCallback == null)
		{
			undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", BindingFlags.NonPublic | BindingFlags.Static);
			if (undoCallback != null)
				undoCallback.SetValue(null, new EditorApplication.CallbackFunction(OnUndoRedo));
		}

		//Toggle editing mode
		if (editing)
		{
			if (GUILayout.Button("Stop Editing"))
				editing = false;
			else
			{
				EditorGUILayout.BeginHorizontal();
				if (GUILayout.Button("Update All"))
					UpdateAll();
				if (GUILayout.Button("Clear"))
					Clear();
				EditorGUILayout.EndHorizontal();
			}
		}
		else if (GUILayout.Button("Edit TileMap"))
			editing = true;

		//Tile Size
		EditorGUI.BeginChangeCheck();
		var newTileSize = EditorGUILayout.FloatField("Tile Size", tileMap.tileSize);
		if (EditorGUI.EndChangeCheck())
		{
			RecordDeepUndo();
			tileMap.tileSize = newTileSize;
			UpdatePositions();
		}

		//Tile Prefab
		EditorGUI.BeginChangeCheck();
		var newTilePrefab = (Transform)EditorGUILayout.ObjectField("Tile Prefab", tileMap.tilePrefab, typeof(Transform), false);
		if (EditorGUI.EndChangeCheck())
		{
			RecordUndo();
			tileMap.tilePrefab = newTilePrefab;
		}

		//Tile Map
		EditorGUI.BeginChangeCheck();
		var newTileSet = (TileSet)EditorGUILayout.ObjectField("Tile Set", tileMap.tileSet, typeof(TileSet), false);
		if (EditorGUI.EndChangeCheck())
		{
			RecordUndo();
			tileMap.tileSet = newTileSet;
		}

		//Tile Prefab selector
		if (tileMap.tileSet != null)
		{
			EditorGUI.BeginChangeCheck();
			var names = new string[tileMap.tileSet.prefabs.Length + 1];
			var values = new int[names.Length + 1];
			names[0] = tileMap.tilePrefab != null ? tileMap.tilePrefab.name : "";
			values[0] = 0;
			for (int i = 1; i < names.Length; i++)
			{
				names[i] = tileMap.tileSet.prefabs[i - 1] != null ? tileMap.tileSet.prefabs[i - 1].name : "";
				//if (i < 10)
				//	names[i] = i + ". " + names[i];
				values[i] = i;
			}
			var index = EditorGUILayout.IntPopup("Select Tile", 0, names, values);
			if (EditorGUI.EndChangeCheck() && index > 0)
			{
				RecordUndo();
				tileMap.tilePrefab = tileMap.tileSet.prefabs[index - 1];
			}
		}

		//Selecting direction
		EditorGUILayout.BeginHorizontal(GUILayout.Width(60));
		EditorGUILayout.PrefixLabel("Direction");
		EditorGUILayout.BeginVertical(GUILayout.Width(20));
		GUILayout.Space(20);
		if (direction == 3)
			GUILayout.Box("<", GUILayout.Width(20));
		else if (GUILayout.Button("<"))
			direction = 3;
		GUILayout.Space(20);
		EditorGUILayout.EndVertical();
		EditorGUILayout.BeginVertical(GUILayout.Width(20));
		if (direction == 0)
			GUILayout.Box("^", GUILayout.Width(20));
		else if (GUILayout.Button("^"))
			direction = 0;
		if (direction == -1)
//.........这里部分代码省略.........
开发者ID:GrimDerp,项目名称:TileEditor,代码行数:101,代码来源:TileMapEditor.cs

示例12: SetValue

 private static void SetValue(object obj, FieldInfo field, object value)
 {
     if (field.FieldType == typeof(bool))
     {
         field.SetValue(obj, (bool)value);
     }
     else if (field.FieldType == typeof(string))
     {
         field.SetValue(obj, (string)value);
     }
     else if (field.FieldType == typeof(long))
     {
         field.SetValue(obj, (long)value);
     }
     else if (field.FieldType == typeof(double))
     {
         field.SetValue(obj, (double)value);
     }
 }
开发者ID:YuukiMochiduki,项目名称:Open-Spherical-Camera-For-Unity,代码行数:19,代码来源:JSONUtil.cs

示例13: bindEvent

 private void bindEvent(string eventName, string handlerName, out FieldInfo eventField, out Delegate eventHandler)
 {
     eventField = null;
     eventHandler = null;
     MethodInfo method = this.Tween.GetType().GetMethod(handlerName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     if (method == null)
     {
         throw new MissingMemberException(string.Concat("Method not found: ", handlerName));
     }
     eventField = this.getField(this.EventSource.GetType(), eventName);
     if (eventField == null)
     {
         throw new MissingMemberException(string.Concat("Event not found: ", eventName));
     }
     try
     {
         MethodInfo methodInfo = eventField.FieldType.GetMethod("Invoke");
         ParameterInfo[] parameters = methodInfo.GetParameters();
         ParameterInfo[] parameterInfoArray = method.GetParameters();
         if ((int)parameters.Length != (int)parameterInfoArray.Length)
         {
             if ((int)parameters.Length <= 0 || (int)parameterInfoArray.Length != 0)
             {
                 throw new InvalidCastException(string.Concat("Event signature mismatch: ", eventHandler));
             }
             eventHandler = this.createDynamicWrapper(this.Tween, eventField.FieldType, parameters, method);
         }
         else
         {
             eventHandler = Delegate.CreateDelegate(eventField.FieldType, this.Tween, method, true);
         }
     }
     catch (Exception exception)
     {
         Debug.LogError(string.Concat("Event binding failed - Failed to create event handler: ", exception.ToString()));
         return;
     }
     Delegate @delegate = Delegate.Combine(eventHandler, (Delegate)eventField.GetValue(this.EventSource));
     eventField.SetValue(this.EventSource, @delegate);
 }
开发者ID:HexHash,项目名称:LegacyRust,代码行数:40,代码来源:dfTweenEventBinding.cs

示例14: unbindEvent

 private void unbindEvent(FieldInfo eventField, Delegate eventDelegate)
 {
     Delegate value = (Delegate)eventField.GetValue(this.EventSource);
     Delegate @delegate = Delegate.Remove(value, eventDelegate);
     eventField.SetValue(this.EventSource, @delegate);
 }
开发者ID:HexHash,项目名称:LegacyRust,代码行数:6,代码来源:dfTweenEventBinding.cs

示例15: RunAutolinking

    /// <summary>
    /// Links a inspector-accessible field to the appropriate value, if possible.
    /// </summary>
    /// <param name="field">The field to set.</param>
    /// <param name="script">The script on which to set the field.</param>
    void RunAutolinking(FieldInfo field, MonoBehaviour script)
    {
        foreach (Attribute a in System.Attribute.GetCustomAttributes(field))
        {
            if (a is AutoLinkAttribute)
            {
                //do autolinking

                AutoLinkAttribute autolinkInfo = (AutoLinkAttribute)a;

                //check if autolinking is valid first
                if(checkExistingLinkValid(field, script, autolinkInfo))
                    return;

                Transform[] parentNodes;

                if (!String.IsNullOrEmpty(autolinkInfo.parentTag))
                {
                    //grab by tag first
                    if (autolinkInfo.parentTag != Tags.untagged)
                    {
                        parentNodes = Array.ConvertAll<GameObject, Transform>(GameObject.FindGameObjectsWithTag(autolinkInfo.parentTag), o => o.transform);
                    }
                    else
                    {
                        //we can't find untagged objects by tag, but we can compare to check if an object is untagged
                        parentNodes = (FindObjectsOfType(typeof(Transform)) as Transform[]).Where(t => t.CompareTag(autolinkInfo.parentTag)).ToArray();
                    }
                    if (!String.IsNullOrEmpty(autolinkInfo.parentName))
                    {
                        //filter by name
                        parentNodes = parentNodes.Where(t => t.name == autolinkInfo.parentName).ToArray();
                    }
                    if (!String.IsNullOrEmpty(autolinkInfo.childPath))
                    {
                        //map to children
                        parentNodes = Array.ConvertAll<Transform, Transform>(parentNodes, t => t.Find(autolinkInfo.childPath));
                        parentNodes = parentNodes.Where(t => t != null).ToArray(); //remove null values
                    }
                }
                else
                {
                    //check that the other two tags aren't empty first
                    if (String.IsNullOrEmpty(autolinkInfo.parentName))
                    {
                        if (String.IsNullOrEmpty(autolinkInfo.childPath))
                        {
                            //if every tag is empty, then we'll limit the search to the local transform
                            Component possibleMatch = script.GetComponentInChildren(field.FieldType);
                            if (possibleMatch != null)
                            {
                                field.SetValue(script, possibleMatch);
                                UnityEditor.EditorUtility.SetDirty(script);
                                return;
                            }
                            else
                                continue;

                        }
                        else
                        {
                            //if only the path is given, use the script's parent as the parent node
                            Transform parent = script.transform.Find(autolinkInfo.childPath);
                            if(parent != null)
                            {
                                Type type = field.FieldType;
                                UnityEngine.Object possibleMatch;
                                if(type == typeof(Transform))
                                    possibleMatch = parent;
                                else if(type == typeof(GameObject))
                                    possibleMatch = parent.gameObject;
                                else
                                    possibleMatch = parent.GetComponent(type);

                                if (possibleMatch != null)
                                {
                                    field.SetValue(script, possibleMatch);
                                    UnityEditor.EditorUtility.SetDirty(script);
                                    return;
                                }
                            }
                            continue;
                        }
                    }
                    else
                    {
                        //start with the universal set of all Transforms; there is no way to get the array of matching names, then filter by name
                        parentNodes = (FindObjectsOfType(typeof(Transform)) as Transform[]).Where(t => t.name == autolinkInfo.parentName).ToArray();
                        if (!String.IsNullOrEmpty(autolinkInfo.childPath))
                        {
                            //map to children
                            parentNodes = Array.ConvertAll<Transform, Transform>(parentNodes, t => t.Find(autolinkInfo.childPath));
                            parentNodes = parentNodes.Where(t => t != null).ToArray(); //remove null values
                        }

//.........这里部分代码省略.........
开发者ID:Reddeyfish,项目名称:Admirals-Forever,代码行数:101,代码来源:AutoLink.cs


注:本文中的FieldInfo.SetValue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。