Ejemplo n.º 1
0
		public static void OnGUI(UnityEngine.Object targetObject){
			EditorGUI.BeginChangeCheck ();
			SerializedObject serializedObject = new SerializedObject (targetObject);
			serializedObject.Update ();
			FieldInfo[] fields;
			if(!fieldsLookup.TryGetValue (targetObject.GetType (),out fields)){
				fields=targetObject.GetPublicFields().OrderBy(field => field.MetadataToken).ToArray();

				fieldsLookup.Add(targetObject.GetType(),fields);
			}
			if(PreferencesEditor.GetBool(Preference.ShowActionTooltips) && !string.IsNullOrEmpty(targetObject.GetTooltip())){
				GUILayout.BeginVertical((GUIStyle)"hostview");

				GUILayout.Label(targetObject.GetTooltip(),FsmEditorStyles.wrappedLabelLeft);
				GUILayout.EndVertical();
			}


			for (int i=0; i< fields.Length; i++) {
				FieldInfo field=fields[i];
				if(field.HasAttribute(typeof(HideInInspector))){
					continue;
				}
				PropertyDrawer drawer=GUIDrawer.GetDrawer(field);
				GUIContent content = field.GetInspectorGUIContent ();
				SerializedProperty property=serializedObject.FindProperty(field.Name);
				if(PreferencesEditor.GetBool(Preference.ShowVariableTooltips) && !string.IsNullOrEmpty(field.GetTooltip())){
					GUILayout.BeginVertical("box");
					GUILayout.Label(field.GetTooltip(),FsmEditorStyles.wrappedLabelLeft);
					GUILayout.EndVertical();
				}

				if(drawer != null){
					drawer.fieldInfo=field;
					drawer.OnGUI(property,content);
				}else{
					int indentLevel=EditorGUI.indentLevel;
					EditorGUI.indentLevel=	typeof(IList).IsAssignableFrom(field.FieldType)?indentLevel+1:indentLevel;
					EditorGUILayout.PropertyField (property, content,true);
					EditorGUI.indentLevel=indentLevel;
				}
			}


			if (EditorGUI.EndChangeCheck()) {
				serializedObject.ApplyModifiedProperties();
				ErrorChecker.CheckForErrors();
			}
		}
Ejemplo n.º 2
0
		public static void ScreenShotComponent(Rect contentRect, UnityEngine.Object target)
		{
			ScreenShots.s_TakeComponentScreenshot = false;
			contentRect.yMax += 2f;
			contentRect.xMin += 1f;
			ScreenShots.SaveScreenShotWithBorder(contentRect, ScreenShots.kWindowBorderColor, target.GetType().Name + "Inspector");
		}
Ejemplo n.º 3
0
    protected virtual void InitializeControlFreakTouchController(UnityEngine.Object touchController)
    {
        if (touchController != null){
            Type inputType = touchController.GetType();

            if (inputType != null){
                this.deadZone = UFE.config.inputOptions.controlFreakDeadZone;
                this.useControlFreak = true;

                // Retrieve the required methods using the Reflection API to avoid
                // compilation errors if Control-Freak's TouchController hasn't been
                // imported into the project. We will cache the method information
                // to call these methods later
                MethodInfo getAxisInfo = inputType.GetMethod(
                    "GetAxis",
                    BindingFlags.Instance | BindingFlags.Public,
                    null,
                    new Type[]{typeof(string)},
                    null
                );

                if (getAxisInfo != null){
                    this.getAxis = delegate(string axis){
                        return (float) getAxisInfo.Invoke(touchController, new object[]{axis});
                    };
                }

                MethodInfo getAxisRawInfo = inputType.GetMethod(
                    "GetAxisRaw",
                    BindingFlags.Instance | BindingFlags.Public,
                    null,
                    new Type[]{typeof(string)},
                    null
                );

                if (getAxisRawInfo != null){
                    this.getAxisRaw = delegate(string axis){
                        return (float) getAxisRawInfo.Invoke(touchController, new object[]{axis});
                    };
                }

                MethodInfo getButtonInfo = inputType.GetMethod(
                    "GetButton",
                    BindingFlags.Instance | BindingFlags.Public,
                    null,
                    new Type[]{typeof(string)},
                    null
                );

                if (getButtonInfo != null){
                    this.getButton = delegate(string button){
                        return (bool) getButtonInfo.Invoke(touchController, new object[]{button});
                    };
                }
            }
        }
    }
Ejemplo n.º 4
0
		public static void CheckForErrors(UnityEngine.Object targetObject){
			if (targetObject == null) {
				return;
			}
			if (targetObject.GetType ()==typeof(StateMachine)) {
				checkingStateMachine = targetObject as StateMachine;			
			}else if(targetObject.GetType()==typeof(State)){
				checkingState=targetObject as State;
			} else if (targetObject.GetType ().IsSubclassOf (typeof(ExecutableNode))) {
				checkingExecutableNode=targetObject as ExecutableNode;			
			}

			FieldInfo[] fields = targetObject.GetType().GetAllFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
			for (int i=0; i<fields.Length; i++) {
				FieldInfo field=fields[i];
				if(field.HasAttribute(typeof(ReferenceAttribute)) || !field.IsSerialized()){
					continue;
				}
				object value=field.GetValue(targetObject);
				if(field.FieldType.IsSubclassOf(typeof(FsmVariable))){
					if(!field.HasAttribute(typeof(NotRequiredAttribute)) &&(value == null || CheckForVariableError(value as FsmVariable,field))){
						FsmError error=new FsmError(FsmError.ErrorType.RequiredField,checkingStateMachine,checkingState,checkingExecutableNode,value as FsmVariable,field);
						if(!ContainsError(error)){
							errorList.Add(error);
						}
					}
				}else if(field.FieldType.IsSubclassOf(typeof(UnityEngine.Object))){
					CheckForErrors(value as UnityEngine.Object);
				}else if(field.FieldType.IsArray){
					var array = value as Array;
					Type elementType = field.FieldType.GetElementType ();
					if(elementType.IsSubclassOf(typeof(UnityEngine.Object))){
						foreach(UnityEngine.Object element in array){
							CheckForErrors(element);
						}
					}
				}
			}
			checkForErrors = false;
		}
Ejemplo n.º 5
0
        public static void LogSingleInstance(UnityEngine.Object instanceToLog, params object[] toLog)
        {
            int instanceId;

            if (instanceDict.TryGetValue(instanceToLog.GetType(), out instanceId))
            {
                if (instanceId == instanceToLog.GetInstanceID())
                    Log(toLog);
            }
            else
            {
                instanceDict[instanceToLog.GetType()] = instanceToLog.GetInstanceID();
                Log(toLog);
            }
        }
Ejemplo n.º 6
0
 internal static string GetTypeName(UnityEngine.Object obj)
 {
   if (obj == (UnityEngine.Object) null)
     return "Object";
   string lower = AssetDatabase.GetAssetPath(obj).ToLower();
   if (lower.EndsWith(".unity"))
     return "Scene";
   if (lower.EndsWith(".guiskin"))
     return "GUI Skin";
   if (Directory.Exists(AssetDatabase.GetAssetPath(obj)))
     return "Folder";
   if (obj.GetType() == typeof (UnityEngine.Object))
     return Path.GetExtension(lower) + " File";
   return ObjectNames.GetClassName(obj);
 }
Ejemplo n.º 7
0
		internal static string GetTypeName(UnityEngine.Object obj)
		{
			string text = AssetDatabase.GetAssetPath(obj).ToLower();
			if (text.EndsWith(".unity"))
			{
				return "Scene";
			}
			if (text.EndsWith(".guiskin"))
			{
				return "GUI Skin";
			}
			if (Directory.Exists(AssetDatabase.GetAssetPath(obj)))
			{
				return "Folder";
			}
			if (obj.GetType() == typeof(UnityEngine.Object))
			{
				return Path.GetExtension(text) + " File";
			}
			return ObjectNames.GetClassName(obj);
		}
Ejemplo n.º 8
0
	/// <summary>
	/// this class will call the validate method of the inspector
	/// </summary>
	/// <param name="theGameObject"></param>
	public static KGFMessageList ValidateEditor(UnityEngine.Object theObject)
	{
		KGFMessageList aMessageList = new KGFMessageList();
		string anObjectName = theObject.GetType().ToString();
		string aTypeName = anObjectName+"Editor";
		Type aType = Type.GetType(aTypeName);
		if(aType != null)
		{
			MethodInfo aMethodInfo = aType.GetMethod("Validate"+aTypeName,System.Reflection.BindingFlags.Static | BindingFlags.Public);
			if(aMethodInfo != null && aMethodInfo.GetParameters().Length == 1)
			{
				object[] aParameters = new object[1];
				aParameters[0] = theObject;
				aMessageList = (KGFMessageList)aMethodInfo.Invoke(null,aParameters);
			}
			else
			{
				if (!itsAlreadySentWarnings.Contains(aTypeName))
				{
					itsAlreadySentWarnings.Add(aTypeName);
					aMessageList.AddWarning("static method Validate"+aTypeName+"() not implemented in: "+aTypeName);
					Debug.LogWarning("static method Validate() not implemented in: "+aTypeName);
				}
			}
		}
		else
		{
			if (!itsAlreadySentWarnings.Contains(aTypeName))
			{
				itsAlreadySentWarnings.Add(aTypeName);
				aMessageList.AddWarning("type: "+aTypeName+" not implemented.");
				Debug.LogWarning("type: "+aTypeName+" not implemented.");
			}
		}
		return aMessageList;
	}
 private static void GeneratePopUpForType(GenericMenu menu, UnityEngine.Object target, bool useFullTargetName, SerializedProperty listener, System.Type[] delegateArgumentsTypes)
 {
   List<UnityEventDrawer.ValidMethodMap> methods = new List<UnityEventDrawer.ValidMethodMap>();
   string targetName = !useFullTargetName ? target.GetType().Name : target.GetType().FullName;
   bool flag = false;
   if (delegateArgumentsTypes.Length != 0)
   {
     UnityEventDrawer.GetMethodsForTargetAndMode(target, delegateArgumentsTypes, methods, PersistentListenerMode.EventDefined);
     if (methods.Count > 0)
     {
       menu.AddDisabledItem(new GUIContent(targetName + "/Dynamic " + string.Join(", ", ((IEnumerable<System.Type>) delegateArgumentsTypes).Select<System.Type, string>((Func<System.Type, string>) (e => UnityEventDrawer.GetTypeName(e))).ToArray<string>())));
       UnityEventDrawer.AddMethodsToMenu(menu, listener, methods, targetName);
       flag = true;
     }
   }
   methods.Clear();
   UnityEventDrawer.GetMethodsForTargetAndMode(target, new System.Type[1]{ typeof (float) }, methods, PersistentListenerMode.Float);
   UnityEventDrawer.GetMethodsForTargetAndMode(target, new System.Type[1]{ typeof (int) }, methods, PersistentListenerMode.Int);
   UnityEventDrawer.GetMethodsForTargetAndMode(target, new System.Type[1]{ typeof (string) }, methods, PersistentListenerMode.String);
   UnityEventDrawer.GetMethodsForTargetAndMode(target, new System.Type[1]{ typeof (bool) }, methods, PersistentListenerMode.Bool);
   UnityEventDrawer.GetMethodsForTargetAndMode(target, new System.Type[1]{ typeof (UnityEngine.Object) }, methods, PersistentListenerMode.Object);
   UnityEventDrawer.GetMethodsForTargetAndMode(target, new System.Type[0], methods, PersistentListenerMode.Void);
   if (methods.Count <= 0)
     return;
   if (flag)
     menu.AddItem(new GUIContent(targetName + "/ "), false, (GenericMenu.MenuFunction) null);
   if (delegateArgumentsTypes.Length != 0)
     menu.AddDisabledItem(new GUIContent(targetName + "/Static Parameters"));
   UnityEventDrawer.AddMethodsToMenu(menu, listener, methods, targetName);
 }
 private static IEnumerable<UnityEventDrawer.ValidMethodMap> CalculateMethodMap(UnityEngine.Object target, System.Type[] t, bool allowSubclasses)
 {
   List<UnityEventDrawer.ValidMethodMap> validMethodMapList = new List<UnityEventDrawer.ValidMethodMap>();
   if (target == (UnityEngine.Object) null || t == null)
     return (IEnumerable<UnityEventDrawer.ValidMethodMap>) validMethodMapList;
   System.Type type = target.GetType();
   List<MethodInfo> list = ((IEnumerable<MethodInfo>) type.GetMethods()).Where<MethodInfo>((Func<MethodInfo, bool>) (x => !x.IsSpecialName)).ToList<MethodInfo>();
   IEnumerable<PropertyInfo> source = ((IEnumerable<PropertyInfo>) type.GetProperties()).AsEnumerable<PropertyInfo>().Where<PropertyInfo>((Func<PropertyInfo, bool>) (x =>
   {
     if (x.GetCustomAttributes(typeof (ObsoleteAttribute), true).Length == 0)
       return x.GetSetMethod() != null;
     return false;
   }));
   list.AddRange(source.Select<PropertyInfo, MethodInfo>((Func<PropertyInfo, MethodInfo>) (x => x.GetSetMethod())));
   using (List<MethodInfo>.Enumerator enumerator = list.GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       MethodInfo current = enumerator.Current;
       System.Reflection.ParameterInfo[] parameters = current.GetParameters();
       if (parameters.Length == t.Length && current.GetCustomAttributes(typeof (ObsoleteAttribute), true).Length <= 0 && current.ReturnType == typeof (void))
       {
         bool flag = true;
         for (int index = 0; index < t.Length; ++index)
         {
           if (!parameters[index].ParameterType.IsAssignableFrom(t[index]))
             flag = false;
           if (allowSubclasses && t[index].IsAssignableFrom(parameters[index].ParameterType))
             flag = true;
         }
         if (flag)
           validMethodMapList.Add(new UnityEventDrawer.ValidMethodMap()
           {
             target = target,
             methodInfo = current
           });
       }
     }
   }
   return (IEnumerable<UnityEventDrawer.ValidMethodMap>) validMethodMapList;
 }
 internal static System.Type FindCustomEditorType(UnityEngine.Object o, bool multiEdit)
 {
   return CustomEditorAttributes.FindCustomEditorTypeByType(o.GetType(), multiEdit);
 }
Ejemplo n.º 12
0
 internal static bool HelpIconButton(Rect position, UnityEngine.Object obj)
 {
   bool flag1 = Unsupported.IsDeveloperBuild();
   bool defaultToMonoBehaviour = !flag1 || obj.GetType().Assembly.ToString().StartsWith("Assembly-");
   bool flag2 = Help.HasHelpForObject(obj, defaultToMonoBehaviour);
   if (!flag2 && !flag1)
     return false;
   Color color = GUI.color;
   GUIContent content = new GUIContent(EditorGUI.GUIContents.helpIcon);
   string helpNameForObject = Help.GetNiceHelpNameForObject(obj, defaultToMonoBehaviour);
   if (flag1 && !flag2)
   {
     GUI.color = Color.yellow;
     string str = (!(obj is MonoBehaviour) ? "sealed partial class-" : "script-") + helpNameForObject;
     content.tooltip = string.Format("Could not find Reference page for {0} ({1}).\nDocs for this object is missing or all docs are missing.\nThis warning only shows up in development builds.", (object) helpNameForObject, (object) str);
   }
   else
     content.tooltip = string.Format("Open Reference for {0}.", (object) helpNameForObject);
   GUIStyle inspectorTitlebarText = EditorStyles.inspectorTitlebarText;
   if (GUI.Button(position, content, inspectorTitlebarText))
     Help.ShowHelpForObject(obj);
   GUI.color = color;
   return true;
 }
Ejemplo n.º 13
0
    internal protected static bool GetMethod(UnityEngine.MonoBehaviour monob, string methodType, out MethodInfo mi)
    {
        mi = null;

        if (monob == null || string.IsNullOrEmpty(methodType))
        {
            return false;
        }

        List<MethodInfo> methods = SupportClass.GetMethods(monob.GetType(), null);
        for (int index = 0; index < methods.Count; index++)
        {
            MethodInfo methodInfo = methods[index];
            if (methodInfo.Name.Equals(methodType))
            {
                mi = methodInfo;
                return true;
            }
        }

        return false;
    }
Ejemplo n.º 14
0
 public SaveGameManager.AssetReference GetAssetId(UnityEngine.Object referencedObject)
 {
     if (referencedObject == null)
     {
         return new SaveGameManager.AssetReference
         {
             index = -1
         };
     }
     Index<string, List<UnityEngine.Object>> index = null;
     Type type = referencedObject.GetType();
     if (!this.assetReferences.TryGetValue(type, out index))
     {
         index = (this.assetReferences[type] = new Index<string, List<UnityEngine.Object>>());
         IEnumerable<UnityEngine.Object> enumerable = Resources.FindObjectsOfTypeAll(type).Except(UnityEngine.Object.FindObjectsOfType(type));
         foreach (UnityEngine.Object current in enumerable)
         {
             index[current.name].Add(current);
         }
     }
     List<UnityEngine.Object> list = null;
     if (!index.TryGetValue(referencedObject.name, out list))
     {
         return new SaveGameManager.AssetReference
         {
             index = -1
         };
     }
     return new SaveGameManager.AssetReference
     {
         index = list.IndexOf(referencedObject),
         name = referencedObject.name,
         type = type.FullName
     };
 }
Ejemplo n.º 15
0
		/** Write a UnityEngine.Object */
		public void SerializeUnityObject ( UnityEngine.Object ob ) {
			
			if ( ob == null ) {
				writer.Write (int.MaxValue);
				return;
			}
			
			int inst = ob.GetInstanceID();
			string name = ob.name;
			string type = ob.GetType().AssemblyQualifiedName;
			string guid = "";
			
			//Write scene path if the object is a Component or GameObject
			Component component = ob as Component;
			GameObject go = ob as GameObject;
			
			if (component != null || go != null) {
				if (component != null && go == null) {
					go = component.gameObject;
				}
				
				UnityReferenceHelper helper = go.GetComponent<UnityReferenceHelper>();
				
				if (helper == null) {
					Debug.Log ("Adding UnityReferenceHelper to Unity Reference '"+ob.name+"'");
					helper = go.AddComponent<UnityReferenceHelper>();
				}
				
				//Make sure it has a unique GUID
				helper.Reset ();
				
				guid = helper.GetGUID ();
			}
			
			
			writer.Write(inst);
			writer.Write(name);
			writer.Write(type);
			writer.Write(guid);
		}
Ejemplo n.º 16
0
    private void DisplayInstanced(UnityEngine.Object obj)
    {
        Type type = obj.GetType();
        FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
        SerializedObject o = new SerializedObject(obj);
        EditorGUILayout.LabelField(obj.name + " (" + type.ToString() + ")", EditorStyles.boldLabel);
        EditorGUI.indentLevel++;
        foreach (FieldInfo field in fields)
        {
            bool hasShowinTweakerAttribute = false;
            foreach (Attribute at in field.GetCustomAttributes(true))
            {
                if (at is TweakableField && !((TweakableField)at).isSharedAmongAllInstances)
                {
                    hasShowinTweakerAttribute = true;
                }
            }
            if (hasShowinTweakerAttribute)
            {
                SerializedProperty prop = o.FindProperty(field.Name);
                if (prop.isArray)
                {
                    DrawArrayProperty(prop);
                }
                else
                {
                    EditorGUILayout.PropertyField(prop);
                }

            }
        }
        o.ApplyModifiedProperties();
        EditorGUI.indentLevel--;
    }
Ejemplo n.º 17
0
 /// <summary>
 /// Retrieves the type of the given object as a string and highlights it.
 /// </summary>
 private static string GetObjectType(UnityEngine.Object a_object)
 {
     return Highlight(a_object.GetType().Name);
 }
Ejemplo n.º 18
0
        static bool IsCodeOrFolder(UnityEngine.Object aObj)
        {
            if (aObj == null) return false;

            if (aObj.GetType() == typeof(UnityEngine.Object)) {
                if (string.IsNullOrEmpty(Path.GetExtension(AssetDatabase.GetAssetPath(aObj)))) {
                    return true;
                }
            }

            if (aObj != null) {
                string path = AssetDatabase.GetAssetPath(aObj);
                if (!string.IsNullOrEmpty(path))
                    return path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase);
            }
            return false;
        }
Ejemplo n.º 19
0
		private ObjectType getAssetType(UnityEngine.Object obj)
		{
			Type type = obj.GetType();
			return typeDic.ContainsKey(type) ? typeDic[type] : ObjectType.None;
		}
		private static IEnumerable<TesityEventDrawer.ValidMethodMap> CalculateMethodMap(UnityEngine.Object target, Type[] t, bool allowSubclasses)
		{
			List<TesityEventDrawer.ValidMethodMap> list = new List<TesityEventDrawer.ValidMethodMap>();
			if (target == null || t == null)
			{
				return list;
			}

			//MODIFIED: This is a test to see if this is where I need to change stuff
			Type type = target.GetType();

			//If it's an ITestityBehaviour type it needs to be handled differently
			if (typeof(ITestityBehaviour).IsAssignableFrom(type))
			{
				//Debug.Log("Targeting Testity Behaviour.");

				type = type.BaseType.GetGenericArguments().First(); //this will grab the EngineScriptComponent child Type used as a generic arg in TestityBehaviour<T>
			}

			List<MethodInfo> list2 = (
				from x in type.GetMethods()
				where !x.IsSpecialName
				select x).ToList<MethodInfo>();
			IEnumerable<PropertyInfo> source = type.GetProperties().AsEnumerable<PropertyInfo>();
			source =
				from x in source
				where x.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length == 0 && x.GetSetMethod() != null
				select x;
			list2.AddRange(
				from x in source
				select x.GetSetMethod());
			foreach (MethodInfo current in list2)
			{
				ParameterInfo[] parameters = current.GetParameters();
				if (parameters.Length == t.Length)
				{
					if (current.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length <= 0)
					{
						if (current.ReturnType == typeof(void))
						{
							bool flag = true;
							for (int i = 0; i < t.Length; i++)
							{
								if (!parameters[i].ParameterType.IsAssignableFrom(t[i]))
								{
									flag = false;
								}
								if (allowSubclasses && t[i].IsAssignableFrom(parameters[i].ParameterType))
								{
									flag = true;
								}
							}
							if (flag)
							{
								list.Add(new TesityEventDrawer.ValidMethodMap
								{
									target = target,
									methodInfo = current
								});
							}
						}
					}
				}
			}
			return list;
		}
Ejemplo n.º 21
0
    static UnityEngine.Object selectComponents(UnityEngine.Object pSelected)
    {
        Component[] lComponents ;
        GameObject lObject;
        if (pSelected is GameObject)
            lObject = (GameObject)pSelected;
        else if (pSelected is Component)
            lObject = ((Component)pSelected).gameObject;
        else
        {
            Debug.Log(pSelected.GetType() + ":" + pSelected);
            return pSelected;
        }

        lComponents = lObject.GetComponents<Component>();

        int lIndex = 0;
        string[] lComponentNames = new string[lComponents.Length+1];
        for (int i = 0; i < lComponents.Length;++i )
        {
            if (lComponents[i])//存在lComponents[i]==null的情况,原因不明
            {
                lComponentNames[i] = lComponents[i].GetType().ToString();
                if (lComponents[i] == pSelected)
                    lIndex = i;
            }
        }
        lComponentNames[lComponents.Length] = "GameObject";
        if(pSelected is GameObject)
        {
            lIndex = lComponents.Length;
        }
        int lNewIndex = EditorGUILayout.Popup(lIndex, lComponentNames);
        //Debug.Log(lNewIndex);
        //Debug.Log(lComponentNames[lNewIndex]);
        if (lNewIndex == lComponents.Length)
        {
            //Debug.Log("GameObject");
            //Debug.Log(lObject.ToString());
            return lObject;
        }
        return lComponents[lNewIndex];
        //return null;
    }
Ejemplo n.º 22
0
		private static IEnumerable<UnityEventDrawer.ValidMethodMap> CalculateMethodMap(UnityEngine.Object target, Type[] t, bool allowSubclasses)
		{
			List<UnityEventDrawer.ValidMethodMap> list = new List<UnityEventDrawer.ValidMethodMap>();
			if (target == null || t == null)
			{
				return list;
			}
			Type type = target.GetType();
			List<MethodInfo> list2 = (
				from x in type.GetMethods()
				where !x.IsSpecialName
				select x).ToList<MethodInfo>();
			IEnumerable<PropertyInfo> source = type.GetProperties().AsEnumerable<PropertyInfo>();
			source = 
				from x in source
				where x.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length == 0 && x.GetSetMethod() != null
				select x;
			list2.AddRange(
				from x in source
				select x.GetSetMethod());
			foreach (MethodInfo current in list2)
			{
				ParameterInfo[] parameters = current.GetParameters();
				if (parameters.Length == t.Length)
				{
					if (current.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length <= 0)
					{
						if (current.ReturnType == typeof(void))
						{
							bool flag = true;
							for (int i = 0; i < t.Length; i++)
							{
								if (!parameters[i].ParameterType.IsAssignableFrom(t[i]))
								{
									flag = false;
								}
								if (allowSubclasses && t[i].IsAssignableFrom(parameters[i].ParameterType))
								{
									flag = true;
								}
							}
							if (flag)
							{
								list.Add(new UnityEventDrawer.ValidMethodMap
								{
									target = target,
									methodInfo = current
								});
							}
						}
					}
				}
			}
			return list;
		}
Ejemplo n.º 23
0
	string[] InspectComponent(UnityEngine.Component component, bool log = false)
	{
		Type type = component.GetType();
		if (log)
		{
			Debug.Log(">> " + type);
		}

		List<string> propertyNames = new List<string>();

		foreach (var f in type.GetFields().Where(f => f.IsPublic))
		{
			bool fieldHasConverter = TypeDescriptor.GetConverter(f.FieldType).CanConvertFrom(typeof(String));
			bool fieldIsUnityObjectSubclass = f.FieldType.IsSubclassOf(typeof(UnityEngine.Object));
			bool fieldTypeIsWrappedProperly = f.FieldType == typeof(Vector3) || f.FieldType == typeof(Quaternion);

			if (fieldHasConverter || fieldIsUnityObjectSubclass || fieldTypeIsWrappedProperly)
			{
				propertyNames.Add(f.Name);

				if (log)
				{
					Debug.Log("Field: " + f.Name + " : " + f.FieldType + "; " + f.GetValue(component));
				}
			}
		}

		var ignoredProperties = new List<String>();
		ignoredProperties.Add("rigidbody");
		ignoredProperties.Add("rigidbody2D");
		ignoredProperties.Add("camera");
		ignoredProperties.Add("light");
		ignoredProperties.Add("animation");
		ignoredProperties.Add("constantForce");
		ignoredProperties.Add("renderer");
		ignoredProperties.Add("audio");
		ignoredProperties.Add("guiText");
		ignoredProperties.Add("networkView");
		ignoredProperties.Add("guiElement");
		ignoredProperties.Add("guiTexture");
		ignoredProperties.Add("collider");
		ignoredProperties.Add("collider2D");
		ignoredProperties.Add("hingeJoint");
		ignoredProperties.Add("particleEmitter");
		ignoredProperties.Add("particleSystem");

		// Ignore this for now
		ignoredProperties.Add("mesh");
		ignoredProperties.Add("material");
		ignoredProperties.Add("materials");
		ignoredProperties.Add("transform");
		ignoredProperties.Add("gameObject");

		foreach (var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(i => !ignoredProperties.Contains(i.Name)))
		{
			bool propHasConverter = TypeDescriptor.GetConverter(p.PropertyType).CanConvertFrom(typeof(String));
			bool propIsUnityObjectSubclass = p.PropertyType.IsSubclassOf(typeof(UnityEngine.Object));
			bool propTypeIsWrappedProperly = p.PropertyType == typeof(Vector3) || p.PropertyType == typeof(Quaternion);

			if (propHasConverter || propIsUnityObjectSubclass || propTypeIsWrappedProperly)
			{
				propertyNames.Add(p.Name);

				if (log)
				{
					Debug.Log("Property: '" + p.Name + "' [" + p.PropertyType + "] Value: " + p.GetValue(component, null));
				}
			}
		}

		return propertyNames.ToArray();
	}
Ejemplo n.º 24
0
		private static void GeneratePopUpForType(GenericMenu menu, UnityEngine.Object target, bool useFullTargetName, SerializedProperty listener, Type[] delegateArgumentsTypes)
		{
			List<UnityEventDrawer.ValidMethodMap> list = new List<UnityEventDrawer.ValidMethodMap>();
			string text = (!useFullTargetName) ? target.GetType().Name : target.GetType().FullName;
			bool flag = false;
			if (delegateArgumentsTypes.Length != 0)
			{
				UnityEventDrawer.GetMethodsForTargetAndMode(target, delegateArgumentsTypes, list, PersistentListenerMode.EventDefined);
				if (list.Count > 0)
				{
					menu.AddDisabledItem(new GUIContent(text + "/Dynamic " + string.Join(", ", (
						from e in delegateArgumentsTypes
						select UnityEventDrawer.GetTypeName(e)).ToArray<string>())));
					UnityEventDrawer.AddMethodsToMenu(menu, listener, list, text);
					flag = true;
				}
			}
			list.Clear();
			UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[]
			{
				typeof(float)
			}, list, PersistentListenerMode.Float);
			UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[]
			{
				typeof(int)
			}, list, PersistentListenerMode.Int);
			UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[]
			{
				typeof(string)
			}, list, PersistentListenerMode.String);
			UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[]
			{
				typeof(bool)
			}, list, PersistentListenerMode.Bool);
			UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[]
			{
				typeof(UnityEngine.Object)
			}, list, PersistentListenerMode.Object);
			UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[0], list, PersistentListenerMode.Void);
			if (list.Count > 0)
			{
				if (flag)
				{
					menu.AddItem(new GUIContent(text + "/ "), false, null);
				}
				if (delegateArgumentsTypes.Length != 0)
				{
					menu.AddDisabledItem(new GUIContent(text + "/Static Parameters"));
				}
				UnityEventDrawer.AddMethodsToMenu(menu, listener, list, text);
			}
		}
Ejemplo n.º 25
0
 public AssetReference GetAssetId(UnityEngine.Object referencedObject)
 {
     if(referencedObject == null) return new AssetReference { index=-1 };
     Index<string, List<UnityEngine.Object>> nameLookup = null;
     var type = referencedObject.GetType();
     if(!assetReferences.TryGetValue(type, out nameLookup))
     {
         assetReferences[type] = nameLookup = new Index<string, List<UnityEngine.Object>>();
         var objectsOfType = Resources.FindObjectsOfTypeAll(type).Except(UnityEngine.Object.FindObjectsOfType(type));
         foreach(var reference in objectsOfType)
         {
             nameLookup[reference.name].Add(reference);
         }
     }
     List<UnityEngine.Object> references = null;
     if(!nameLookup.TryGetValue(referencedObject.name, out references))
     {
         return new AssetReference { index = -1 };
     }
     return new AssetReference { index = references.IndexOf(referencedObject), name = referencedObject.name, type = type.FullName };
 }
		public OCObjectMapInfo (UnityEngine.GameObject gameObject)
		{
			UnityEngine.Debug.Log ("OCObjectMapInfo::OCObjectMapInfo, passed object is of type: " + gameObject.GetType().ToString () + ", and name " + gameObject.name);
			
			_id = gameObject.GetInstanceID().ToString();
			
//			// Get id of a game object
//			_id = gameObject.GetInstanceID ().ToString ();
			// Get name
			_name = gameObject.name;
			// TODO: By default, we are using object type.
			_type = OCEmbodimentXMLTags.ORDINARY_OBJECT_TYPE;

			// Convert from unity coordinate to OAC coordinate.

			this.position = Utility.VectorUtil.ConvertToOpenCogCoord (gameObject.transform.position);
			// Get rotation
			_rotation = new Utility.Rotation (gameObject.transform.rotation);
			// Calculate the velocity later
			_velocity = UnityEngine.Vector3.zero;

			// Get size
			if (gameObject.collider != null) {
				// Get size information from collider.
				_width = gameObject.collider.bounds.size.z;
				_height = gameObject.collider.bounds.size.y;
				_length = gameObject.collider.bounds.size.x;
			} else {
				OCLogger.Warn ("No collider for gameobject " + gameObject.name + ", assuming a point.");

				// Set default value of the size.
				_width = 0.1f;
				_height = 0.1f;
				_length = 0.1f;
			}

			if (gameObject.tag == "OCAGI") {
				// This is an OC avatar, we will use the brain id instead of unity id.
				OCConnectorSingleton connector = OCConnectorSingleton.Instance;

				if (connector != null)
				{
					_id = connector.BrainID;
					_type = OCEmbodimentXMLTags.PET_OBJECT_TYPE;
				}
				
				UnityEngine.Debug.Log ("Just made an OCObjectMapInfo stating the AGI is at [" + this.position.x + ", " + this.position.y + ", " + this.position.z + "]");

			} else if (gameObject.tag == "OCNPC") {
				// This is a human player avatar.
				_type = OCEmbodimentXMLTags.AVATAR_OBJECT_TYPE;
				_length = OCObjectMapInfo.DEFAULT_AVATAR_LENGTH;
				_width = OCObjectMapInfo.DEFAULT_AVATAR_WIDTH;
				_height = OCObjectMapInfo.DEFAULT_AVATAR_HEIGHT;
			}

			if (gameObject.tag == "OCNPC" || gameObject.tag == "OCAGI" || gameObject.tag == "Player")
			{
				if (_height > 1.1f) // just to make sure that the center point of the character will not be in the block where the feet are
				{
					this.position = new UnityEngine.Vector3(this.position.x, this.position.y, this.position.z + 1.0f);	
				}
			}

						
			if (gameObject.name == "Hearth")
			{
				this.AddProperty("petHome", "TRUE", System.Type.GetType("System.Boolean"));	
			}

			// Get weight
			if (gameObject.rigidbody != null) {
				_weight = gameObject.rigidbody.mass;
			} else {
				_weight = 0.0f;
			}
			
			if (gameObject.GetComponent<OpenCog.Extensions.OCConsumableData>() != null)
			{
				UnityEngine.Debug.Log ("Adding edible and foodbowl tags to '" + gameObject.name + "' with ID " + gameObject.GetInstanceID());
				this.AddProperty ("edible", "TRUE", System.Type.GetType ("System.Boolean"));
				this.AddProperty ("pickupable", "TRUE", System.Type.GetType ("System.Boolean"));
				this.AddProperty ("holder", "none", System.Type.GetType ("System.String"));
			}

			// Get a property manager instance
			// TODO: may need to re-enable this for other object types.
//			OCPropertyManager manager = gameObject.GetComponent<OCPropertyManager> () as OCPropertyManager;
//			if (manager != null) {
//				// Copy all OC properties from the manager, if any.
//				foreach (OpenCog.Serialization.OCPropertyField ocp in manager.propertyList) {
//					this.AddProperty (ocp.Key, ocp.value, ocp.valueType);
//				}
//			}

			this.AddProperty ("visibility-status", "visible", System.Type.GetType("System.String"));
			this.AddProperty ("detector", "true", System.Type.GetType("System.Boolean"));
			
			string gameObjectName = gameObject.name;
			if (gameObjectName.Contains ("("))
				gameObjectName = gameObjectName.Remove (gameObjectName.IndexOf ('('));



			// For Einstein puzzle
			if (gameObject.name.Contains("_man"))
			{
				_id = _name;
				this.AddProperty ("class", "people", System.Type.GetType("System.String"));
			}
			else
			    this.AddProperty ("class", gameObjectName, System.Type.GetType("System.String"));
		}
Ejemplo n.º 27
0
		internal void Show(UnityEngine.Object obj, Type requiredType, SerializedProperty property, bool allowSceneObjects, List<int> allowedInstanceIDs)
		{
			this.m_AllowSceneObjects = allowSceneObjects;
			this.m_IsShowingAssets = true;
			this.m_AllowedIDs = allowedInstanceIDs;
			string text = string.Empty;
			if (property != null)
			{
				text = property.objectReferenceTypeString;
				obj = property.objectReferenceValue;
				UnityEngine.Object targetObject = property.serializedObject.targetObject;
				if (targetObject != null && EditorUtility.IsPersistent(targetObject))
				{
					this.m_AllowSceneObjects = false;
				}
			}
			else
			{
				if (requiredType != null)
				{
					text = requiredType.Name;
				}
			}
			if (this.m_AllowSceneObjects)
			{
				if (obj != null)
				{
					if (typeof(Component).IsAssignableFrom(obj.GetType()))
					{
						obj = ((Component)obj).gameObject;
					}
					this.m_IsShowingAssets = (EditorUtility.IsPersistent(obj) || ObjectSelector.GuessIfUserIsLookingForAnAsset(text, false));
				}
				else
				{
					this.m_IsShowingAssets = ObjectSelector.GuessIfUserIsLookingForAnAsset(text, true);
				}
			}
			else
			{
				this.m_IsShowingAssets = true;
			}
			this.m_DelegateView = GUIView.current;
			this.m_RequiredType = text;
			this.m_SearchFilter = string.Empty;
			this.m_OriginalSelection = obj;
			this.m_ModalUndoGroup = Undo.GetCurrentGroup();
			ContainerWindow.SetFreezeDisplay(true);
			base.ShowWithMode(ShowMode.AuxWindow);
			base.title = "Select " + text;
			Rect position = this.m_Parent.window.position;
			position.width = EditorPrefs.GetFloat("ObjectSelectorWidth", 200f);
			position.height = EditorPrefs.GetFloat("ObjectSelectorHeight", 390f);
			base.position = position;
			base.minSize = new Vector2(200f, 335f);
			base.maxSize = new Vector2(10000f, 10000f);
			this.SetupPreview();
			base.Focus();
			ContainerWindow.SetFreezeDisplay(false);
			this.m_FocusSearchFilter = true;
			this.m_Parent.AddToAuxWindowList();
			int num = (!(obj != null)) ? 0 : obj.GetInstanceID();
			if (property != null && property.hasMultipleDifferentValues)
			{
				num = 0;
			}
			if (ObjectSelector.ShouldTreeViewBeUsed(text))
			{
				this.m_ObjectTreeWithSearch.Init(base.position, this, new UnityAction<ObjectTreeForSelector.TreeSelectorData>(this.CreateAndSetTreeView), new UnityAction<TreeViewItem>(this.TreeViewSelection), new UnityAction(this.ItemWasDoubleClicked), num, 0);
			}
			else
			{
				this.InitIfNeeded();
				this.m_ListArea.InitSelection(new int[]
				{
					num
				});
				if (num != 0)
				{
					this.m_ListArea.Frame(num, true, false);
				}
			}
		}
Ejemplo n.º 28
0
    private void DoDrop( UnityEngine.Object dragObject)
    {
        // Gameobject
        if (dragObject.GetType() == typeof(GameObject)){
            GameObject obj = (GameObject)dragObject;
            SpriteRenderer srs = obj.GetComponent<SpriteRenderer>();

            // Complexe sprite
            if (srs!=null){
                string path = AssetDatabase.GetAssetPath( srs.sprite.texture);
                string guid = AssetDatabase.AssetPathToGUID( path);
                AddRefTile(guid,false,Tile.TileType.ComplexeSprite,srs.sprite,obj);
            }

            // Prefab
            if (srs==null){
                foreach( Transform t in obj.transform){
                    srs = t.GetComponent<SpriteRenderer>();
                    if (srs!=null){
                        string path = AssetDatabase.GetAssetPath( srs.sprite.texture);
                        string guid = AssetDatabase.AssetPathToGUID( path);
                        AddRefTile(guid,false,Tile.TileType.PrefabSprite,srs.sprite,obj);
                    }
                }
            }
        }

        // Sprite
        if (dragObject.GetType() == typeof(Sprite)){
            string path = AssetDatabase.GetAssetPath( dragObject);
            string guid = AssetDatabase.AssetPathToGUID( path);
            AddRefTile(guid,false,Tile.TileType.Sprite, (Sprite)dragObject );
            return;
        }

        // Multi sprite
        if (dragObject.GetType() == typeof(Texture2D)){

            Texture2D tex = (Texture2D)dragObject;

            // Get the path of the texture
            string path = AssetDatabase.GetAssetPath( tex.GetInstanceID());

            // Get the textureImporter object
            TextureImporter textureImporter = AssetImporter.GetAtPath(  path ) as TextureImporter;

            if (textureImporter.spriteImportMode != SpriteImportMode.None ){
                UnityEngine.Object[] sprites = AssetDatabase.LoadAllAssetsAtPath(path);

                if (sprites.Length>0){
                    if (sprites.Length>1){
                        for (int i=1;i<sprites.Length;i++){
                            AddRefTile("",true,Tile.TileType.Sprite,(Sprite)sprites[i],null );
                        }
                    }
                }
            }

            return;
        }
    }
Ejemplo n.º 29
0
        // ***********************************************************************************
        // CONSTRUCTOR
        // ***********************************************************************************

        public HOTweenData(int p_creationTime, GameObject p_targetRoot, UnityEngine.Object p_target, string p_targetPath)
        {
            targetRoot = p_targetRoot;
            target = p_target;
            _targetPath = p_targetPath;
            creationTime = p_creationTime;

            Type t = p_target.GetType();
#if UNITY_EDITOR
            _targetType = t.FullName + ", " + t.Assembly.GetName().Name;
#endif
            targetName = targetPath.Substring(targetPath.LastIndexOf(".") + 1);
            propDatas = new List<HOPropData>();
        }
Ejemplo n.º 30
0
 public static float ComputeVolume(UnityEngine.Collider coll)
 {
     if (coll != null) {
         UnityEngine.CapsuleCollider collider = coll as UnityEngine.CapsuleCollider;
         if (collider != null) {
             UnityEngine.Vector3 lossyScale = collider.transform.lossyScale;
             float num = collider.height * lossyScale.y;
             float num2 = collider.radius * UnityEngine.Mathf.Max(lossyScale.x, lossyScale.z);
             float num3 = (3.141593f * num2) * num2;
             float num4 = num3 * num;
             float num5 = (num3 * num2) * 1.333333f;
             return (num4 + num5);
         }
         UnityEngine.SphereCollider collider2 = coll as UnityEngine.SphereCollider;
         if (collider2 != null) {
             UnityEngine.Vector3 vector2 = collider2.transform.lossyScale;
             float[] values = new float[] { vector2.x, vector2.y, vector2.z };
             float num6 = collider2.radius * UnityEngine.Mathf.Max(values);
             return (4.18879f * ((num6 * num6) * num6));
         }
         UnityEngine.BoxCollider collider3 = coll as UnityEngine.BoxCollider;
         if (collider3 != null) {
             UnityEngine.Vector3 vector3 = collider3.transform.lossyScale;
             UnityEngine.Vector3 size = collider3.size;
             return (((size.x * vector3.x) * (size.y * vector3.y)) * (size.z * vector3.z));
         }
         UnityEngine.Debug.LogWarning("Not implemented for " + coll.GetType() + " type!");
     }
     return 0f;
 }