public static object GetObject(UnityEngine.Object obj) { if (obj == null) { return(null); } var property = IL.Help.GetProperty(obj.GetType(), "refType"); if (property == null) { L.LogErrorFormat("CSharpAgent type:{0} not find refType!", obj.GetType().FullName); return(null); } var refType = property.GetValue(obj) as RefType; if (refType == null) { L.LogError("refType == null"); return(null); } return(refType.Instance); }
public override void Execute() { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; Object[] objects = Object.FindObjectsOfType <Object>(); Object obj = objects.FirstOrDefault(o => o.GetInstanceID() == InstanceId); if (obj == null) { return; } Type type = obj.GetType(); MemberInfo[] members = type.GetMember(MemberName, bindingFlags); MemberInfo member = members.Single(); PropertyInfo property = member as PropertyInfo; if (property != null) { property.SetValue(obj, Value.Object, null); return; } FieldInfo field = member as FieldInfo; if (field != null) { field.SetValue(obj, Value.Object); return; } throw new NotSupportedException(member.GetType().FullName); }
public static AssetTypeIdentifier Of(UnityEngine.Object asset) { var prefabType = PrefabUtility.GetPrefabType(asset); var assetType = asset.GetType(); return(new AssetTypeIdentifier(assetType, prefabType)); }
public static void LogWarning(string message, UnityEngine.Object context) { if (IsActive(context.GetType())) { UnityEngine.Debug.LogWarning(message, TryToGetGameObjectReference(context)); } }
public static MToken GetValueFromBinder(UnityEngine.Object binderObject) { var method = binderObject.GetType().GetMethod("GetData"); var value = method.Invoke(binderObject, null); return((MToken)value); }
public static Guid GetGuid(this UnityEngine.Object obj) { if (!UnityEditor.AssetDatabase.TryGetGUIDAndLocalFileIdentifier(obj, out var guid, out long fileId)) { return(Guid.Empty); } if (string.IsNullOrEmpty(guid) || guid == "00000000000000000000000000000000") { // Special case for memory textures if (obj is UnityEngine.Texture texture) { return(texture.imageContentsHash.ToGuid()); } Debug.LogWarning($"Could not get {nameof(Guid)} for object type '{obj.GetType().FullName}'."); return(Guid.Empty); } // Merge asset database guid and file identifier var bytes = new byte[guid.Length + sizeof(long)]; Encoding.ASCII.GetBytes(guid).CopyTo(bytes, 0); BitConverter.GetBytes(fileId).CopyTo(bytes, guid.Length); return(GuidUtility.NewGuid(bytes)); }
public static void ThrowNullReferenceExceptionWhenFieldNotInitialized(Object obj, UnityEngine.Object owner, string fieldName) { // Everything is ok if (obj != null) { return; } // Worst case: Improper use of this method if (owner == null) { throw new ArgumentException($"Unknown owner {fieldName}"); } if (string.IsNullOrEmpty(fieldName)) { throw new ArgumentException($"Unknown field name {fieldName}"); } var type = owner.GetType(); // Disable component if possible var propertyInfo = type.GetProperty("enabled"); if (propertyInfo != null) { propertyInfo.SetValue(owner, false); } // Hint for non-programmers that something was not set via the inspector throw new NullReferenceException( $"{owner.name}, {type}, {fieldName}" ); }
public override bool IsSearchMatch(Object asset, string searchQuery) { searchQuery = searchQuery.ToLower(); return(GetObjectName(asset).Contains(searchQuery) || asset.GetType().Name.ToLower().Contains(searchQuery)); }
public static string ToSafeString(this UnityObject uo) { if (ReferenceEquals(uo, null)) { return("(null)"); } if (!UnityThread.allowsAPI) { return(uo.GetType().Name); } if (uo == null) { return("(Destroyed)"); } try { return(uo.name); } catch (Exception ex) { return($"({ex.GetType().Name} in ToString: {ex.Message})"); } }
public static List <SerializedFieldData> Get([NotNull] Object target, [CanBeNull] Type ignoreFieldsInBaseType = null) { var type = target.GetType(); var serializedFields = new List <SerializedFieldData>(); while (type != Types.MonoBehaviour && type != Types.UnityObject && type != Types.Component && type != Types.Behaviour && type != ignoreFieldsInBaseType) { var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); for (int n = fields.Length - 1; n >= 0; n--) { var field = fields[n]; if (field.IsInitOnly || field.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length > 0) { continue; } var value = field.GetValue(target); if (value != null) { serializedFields.Add(new SerializedFieldData(field.Name, value)); } } type = type.BaseType; } return(serializedFields); }
private static BaseInvokableCall GetObjectCall(UnityEngine.Object target, MethodInfo method, ArgumentCache arguments) { Type type = typeof(UnityEngine.Object); if (!string.IsNullOrEmpty(arguments.unityObjectArgumentAssemblyTypeName)) { type = (Type.GetType(arguments.unityObjectArgumentAssemblyTypeName, false) ?? typeof(UnityEngine.Object)); } Type typeFromHandle = typeof(CachedInvokableCall <>); Type type2 = typeFromHandle.MakeGenericType(new Type[] { type }); ConstructorInfo constructor = type2.GetConstructor(new Type[] { typeof(UnityEngine.Object), typeof(MethodInfo), type }); UnityEngine.Object @object = arguments.unityObjectArgument; if (@object != null && !type.IsAssignableFrom(@object.GetType())) { @object = null; } return(constructor.Invoke(new object[] { target, method, @object }) as BaseInvokableCall); }
/// <summary> /// Asserts if obj is null. Works only when Debugger is Enabled. /// </summary> /// <param name="obj">Object to check.</param> /// <param name="name">Name of a object</param> /// <param name="context">Context for a check (usually containing class).</param> public static void AssertNotNull(object obj, string name, Object context) { if (Enabled && (obj == null || obj.Equals(null))) { Debug.LogError(name + " in object " + context.name + " ( " + context.GetType() + " ) is null!", context); } }
public void Dispatch(Object asset, PostprocessEventArgs args) { UnityEngine.Assertions.Assert.AreEqual(asset.GetType(), typeof(TAsset)); AssetHandler(asset, args); TypedAssetHandler((TAsset)asset, args); }
public static void IsSetInEditor <T>(T obj, UnityEngine.Object context) where T : class { if (obj is null) { UnityEngine.Debug.LogError(typeof(T).Name + " is not set for " + context.GetType().Name, context); } }
public static Object[] Replace(this Object[] @this, Object item) { List <Object> list = @this.ToList(); list.RemoveAll(i => i.GetType() == item.GetType()); list.Add(item); return(list.ToArray()); }
public static MonoScript CashedMono(this UnityEngine.Object anyUnityObject, ref MonoScript monoScript) { if (monoScript == null) { monoScript = GetMonoScript(anyUnityObject.GetType()); } return(monoScript); }
public AssetMetadata(Object asset) { Asset = asset; var type = asset.GetType(); SingletonAssetAttribute = type.GetCustomAttribute <SingletonAssetAttribute>(); CreateAssetAutomaticallyAttribute = type.GetCustomAttribute <CreateAssetAutomaticallyAttribute>(); }
// Ideal solution would be getting title via // ProjectSettingsBaseEditor's targetTitle property. public static string GetProjectSettingsTargetTitle(UnityEngine.Object obj) { var objType = obj.GetType(); if (objType == inputManagerType) { return("InputManager"); } else if (objType == tagManagerType) { return("Tags & Layers"); } else if (objType == audioManagerType) { return("AudioManager"); } else if (objType == timeManagerType) { return("TimeManager"); } else if (objType == playerSettingsType) { return("PlayerSettings"); } else if (objType == physicsManagerType) { return("PhysicsManager"); } else if (objType == physics2DSettingsType) { return("Physics2DSettings"); } else if (objType == qualitySettingsType) { return("QualitySettings"); } else if (objType == graphicsSettingsType) { return("GraphicsSettings"); } else if (objType == networkManagerType) { return("NetworkManager"); } else if (objType == editorSettingsType) { return("Editor Settings"); } else if (objType == monoManagerType) { return("Script Execution Order"); } else if (objType == presetManagerType) { return("PresetManager"); } return(null); }
internal static bool IsUnityAssembly(Object target) { if (target == null) { return(false); } System.Type type = target.GetType(); return(IsUnityAssembly(type)); }
// GetSP Info From SerializedProperty static SPInfo <T> GetSPInfoFrom <T>(SerializedProperty property) where T : Attribute { Object targetObject = property.serializedObject.targetObject; Type type = targetObject.GetType(); FieldInfo field = type.GetField(property.name, k_BindingFlags); T attr = Attribute.GetCustomAttribute(field, typeof(T)) as T; return(new SPInfo <T>(targetObject, type, field, attr)); }
public override bool IsSearchMatch(Object asset, string searchQuery) { var c = (CurrencyDefinition)asset; searchQuery = searchQuery.ToLower(); return(c.singleName.ToLower().Contains(searchQuery) || c.pluralName.ToLower().Contains(searchQuery) || asset.GetType().Name.ToLower().Contains(searchQuery)); }
public static void Type <T>( UnityEngine.Object instance, string paramName) { if (instance is T == false) { ThrowArgumentException(paramName, StringResources.SuppliedTypeIsNotAGivenType(instance.GetType(), typeof(T))); } }
/// <summary> /// Opens a reference web page generated for the specified object. /// </summary> /// <remarks>This method assumes the page in question was generated via SHFB.</remarks> /// <param name="obj">A <see cref="UnityEngine.Object"/>.</param> /// <param name="product">Product name (first parameter in format string).</param> /// <param name="urlFormat"> /// A <see cref="System.String"/> specifying the URL format. Index 0 is for the product name and index 1 is for /// the type name. /// </param> public static void OpenReferencePage( this UnityEngine.Object obj, string product, string urlFormat = "http://candlelightinteractive.com/docs/{0}/html/T_{1}.htm?ref=editor" ) { UnityEngine.Application.OpenURL( string.Format(urlFormat, product, obj.GetType().FullName.Replace('.', '_')) ); }
/// <summary> /// Returns an identifier for the given asset. /// </summary> static public StringHash32 GetAssetIdentifier(UnityEngine.Object inObject) { if (inObject.IsReferenceNull()) { return(StringHash32.Null); } #if UNITY_EDITOR string assetPath = AssetDatabase.GetAssetPath(inObject); if (AssetDatabase.IsMainAsset(inObject)) { return(string.Format("{0}::{1}", inObject.GetType().Name, assetPath)); } return(string.Format("{0}::{1}->{2}", inObject.GetType().Name, assetPath, inObject.name)); #else return(string.Format("{0}::{1}({2})", inObject.GetType().Name, inObject.name, inObject.GetInstanceID())); #endif // UNITY_EDITOR }
internal static bool TryReflectMethod(out MethodInfo methodInfo, out UnityReflectionException exception, UnityObject reflectionTarget, string name, Type[] parameterTypes) { #if !NETFX_CORE methodInfo = null; Type type = reflectionTarget.GetType(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; if (parameterTypes != null) // Explicit matching { methodInfo = type.GetMethod(name, flags, null, parameterTypes, null); if (methodInfo == null) { methodInfo = type.GetExtensionMethods() .Where(extension => extension.Name == name) .Where(extension => Enumerable.SequenceEqual(extension.GetParameters().Select(paramInfo => paramInfo.ParameterType), parameterTypes)) .FirstOrDefault(); } if (methodInfo == null) { exception = new UnityReflectionException(string.Format("No matching method found: '{0}.{1} ({2})'", type.Name, name, string.Join(", ", parameterTypes.Select(t => t.Name).ToArray()))); return false; } } else // Implicit matching { var normalMethods = type.GetMember(name, MemberTypes.Method, flags).OfType<MethodInfo>().ToList(); var extensionMethods = type.GetExtensionMethods().Where(extension => extension.Name == name).ToList(); var methods = new List<MethodInfo>(); methods.AddRange(normalMethods); methods.AddRange(extensionMethods); if (methods.Count == 0) { exception = new UnityReflectionException(string.Format("No matching method found: '{0}.{1}'", type.Name, name)); return false; } if (methods.Count > 1) { exception = new UnityReflectionException(string.Format("Multiple method signatures found for '{0}.{1}'\nSpecify the parameter types explicitly.", type.FullName, name)); return false; } methodInfo = methods[0]; } exception = null; return true; #else throw new Exception("Reflection is not supported in .NET Core."); #endif }
internal static bool TryReflectMethod(out MethodInfo methodInfo, out UnityReflectionException exception, UnityObject reflectionTarget, string name, Type[] parameterTypes) { #if !NETFX_CORE methodInfo = null; Type type = reflectionTarget.GetType(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; if (parameterTypes != null) // Explicit matching { methodInfo = type.GetMethod(name, flags, null, parameterTypes, null); if (methodInfo == null) { methodInfo = type.GetExtensionMethods() .Where(extension => extension.Name == name) .Where(extension => Enumerable.SequenceEqual(extension.GetParameters().Select(paramInfo => paramInfo.ParameterType), parameterTypes)) .FirstOrDefault(); } if (methodInfo == null) { exception = new UnityReflectionException(string.Format("No matching method found: '{0}.{1} ({2})'", type.Name, name, string.Join(", ", parameterTypes.Select(t => t.Name).ToArray()))); return(false); } } else // Implicit matching { var normalMethods = type.GetMember(name, MemberTypes.Method, flags).OfType <MethodInfo>().ToList(); var extensionMethods = type.GetExtensionMethods().Where(extension => extension.Name == name).ToList(); var methods = new List <MethodInfo>(); methods.AddRange(normalMethods); methods.AddRange(extensionMethods); if (methods.Count == 0) { exception = new UnityReflectionException(string.Format("No matching method found: '{0}.{1}'", type.Name, name)); return(false); } if (methods.Count > 1) { exception = new UnityReflectionException(string.Format("Multiple method signatures found for '{0}.{1}'\nSpecify the parameter types explicitly.", type.FullName, name)); return(false); } methodInfo = methods[0]; } exception = null; return(true); #else throw new Exception("Reflection is not supported in .NET Core."); #endif }
public override bool Execute(Player player) { if (Obj == null || MethodName == string.Empty) { return(true); } else { return((bool)Obj.GetType().GetMethod(MethodName).Invoke(Obj, new object[] { player })); } }
public static void Recevive(string _key, MessageType _type, UnityEngine.Object _content) { if (_content.GetType() == typeof(UnityEngine.GameObject)) { MessageModule.instance.Recevive(_key, _type, (UnityEngine.GameObject)_content); } else { MessageModule.instance.Recevive(_key, _type, _content); } }
private static Type GetTypeFromObjectReference(UnityEngine.Object o) { if (o is DataContext) { return((o as DataContext).Type); } else { return(o.GetType()); } }
/// <summary> /// Wraps a Resource into a Node /// </summary> /// <param name="injector"></param> /// <param name="resource"></param> /// <param name="name"></param> internal ResourceNode(Injector injector, UnityEngine.Object resource, string name) : base(injector) { // Check if resource is null if (resource != null) { // Store resource information this.resource = resource; this.type = resource.GetType(); } this.name = name; }
public void SetObject(UnityEngine.Object obj) { objectValue = obj; if (obj != null) { stringValue = obj.GetType().FullName; } values = null; this.type = SerializedType.Object; }
internal static bool TryReflectVariable(out MemberInfo variableInfo, out UnityReflectionException exception, UnityObject reflectionTarget, string name) { #if !NETFX_CORE variableInfo = null; Type type = reflectionTarget.GetType(); MemberTypes types = MemberTypes.Property | MemberTypes.Field; BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; MemberInfo[] variables = type.GetMember(name, types, flags); if (variables.Length == 0) { exception = new UnityReflectionException(string.Format("No matching field or property found: '{0}.{1}'", type.Name, name)); return false; } variableInfo = variables[0]; // Safe, because there can't possibly be more than one variable of the same name exception = null; return true; #else throw new Exception("Reflection is not supported in .NET Core."); #endif }
/// <summary> /// Asserts if obj is null. Works only when Debugger is Enabled. /// </summary> /// <param name="obj">Object to check.</param> /// <param name="name">Name of a object</param> /// <param name="context">Context for a check (usually containing class).</param> public static void AssertNotNull(object obj, string name, Object context) { if (Enabled && (obj == null || obj.Equals(null))) { Debug.LogError(name + " in object " + context.name + " ( " + context.GetType() + " ) is null!", context); } }