public static void UpdatePerahpsReferenceObjectList(MonoBehaviour component, List<PerhapsReferenceObject> list) { // analytics source code. var monoScript = MonoScript.FromMonoBehaviour(component); var uniqueClassList = SceneObjectUtility.SceneUniqueComponentName(); foreach (var text in monoScript.text.Split(';')) { foreach( var methodPattern in getComponentFunctionPattern) { Match m = Regex.Match (text, methodPattern); if (m.Success) { var className = m.Groups ["call"].ToString (); if(! list.Exists (item => item.compType == component.GetType() && item.referenceMonobehaviourName == className) ) { var method = new PerhapsReferenceObject () { compType = component.GetType(), referenceMonobehaviourName = className, monoscript = monoScript, }; list.Add (method); uniqueClassList.RemoveAll( item => item.Name == className ); } } } foreach( var className in uniqueClassList) { if( component.GetType() == className ) continue; var result = text.IndexOf(className.Name ) ; if(result != -1 && result != 0 ) { if(! list.Exists (item => item.compType == component.GetType() && item.referenceMonobehaviourName == className.Name) ) { var method = new PerhapsReferenceObject () { compType = component.GetType(), referenceMonobehaviourName = className.Name, monoscript = monoScript, }; list.Add (method); continue; } } } } }
/// <summary> /// Validates collider settings. /// </summary> protected List<ValidationResult> CheckCollider(MonoBehaviour m) { List<ValidationResult> result = new List<ValidationResult> (); if (m.GetComponent<Collider2D>() == null) { result.Add (new ValidationResult("Found a " + m.GetType().Name + " but it did not have a Collider2D attached.", MessageType.Warning)); } else if (!m.GetComponent<Collider2D>().isTrigger) { result.Add (new ValidationResult("Found a " + m.GetType().Name + " but the collider2D was not a trigger.", MessageType.Info)); } return result; }
private void ProcessBehaviour(MonoBehaviour behaviour) { Type componentType = behaviour.GetType(); ClassDataHolder data = ReflectionDataCache.GetClassData(componentType); for (int i = 0; i < data.PropertyInfos.Length; i++) { PropertyInfo property = data.PropertyInfos[i]; if (data.PropertyAttributes[i]) continue; ThrowIfNotNull(property.GetValue(behaviour, null)); object dependency = _context.Resolve(property.PropertyType); property.SetValue(behaviour, dependency, null); } for (int i = 0; i < data.FieldInfos.Length; i++) { FieldInfo field = data.FieldInfos[i]; if (data.FieldAttributes[i]) continue; ThrowIfNotNull(field.GetValue(behaviour)); object dependency = _context.Resolve(field.FieldType); field.SetValue(behaviour, dependency); } }
private static List<NotNullViolation> FindErroringFields(MonoBehaviour sourceMB) { if (sourceMB == null) { throw new System.ArgumentNullException("MonoBehaviour is null. It likely references" + " a script that's been deleted."); } List<NotNullViolation> erroringFields = new List<NotNullViolation>(); // Add null NotNull fields List<FieldInfo> notNullFields = ReflectionUtility.GetFieldsWithAttributeFromType<NotNullAttribute>( sourceMB.GetType(), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo notNullField in notNullFields) { object fieldObject = notNullField.GetValue(sourceMB); if (fieldObject == null || fieldObject.Equals(null)) { erroringFields.Add(new NotNullViolation(notNullField, sourceMB)); } } // Remove NotNullViolations for prefabs with IgnorePrefab bool isObjectAPrefab = PrefabUtility.GetPrefabType(sourceMB.gameObject) == PrefabType.Prefab; List<NotNullViolation> violationsToIgnore = new List<NotNullViolation>(); if (isObjectAPrefab) { // Find all violations that should be overlooked. foreach (NotNullViolation errorField in erroringFields) { FieldInfo fieldInfo = errorField.FieldInfo; foreach (Attribute attribute in Attribute.GetCustomAttributes(fieldInfo)) { if (attribute.GetType() == typeof(NotNullAttribute)) { if (((NotNullAttribute)attribute).IgnorePrefab) { violationsToIgnore.Add(errorField); } } } } foreach (NotNullViolation violation in violationsToIgnore) { erroringFields.Remove(violation); } } return erroringFields; }
public static void InjectMonoBehaviour( DiContainer container, MonoBehaviour monoBehaviour, IEnumerable<object> extraArgs) { // null if monobehaviour link is broken if (monoBehaviour != null && monoBehaviour.enabled) { using (container.PushLookup(monoBehaviour.GetType())) { FieldsInjecter.Inject(container, monoBehaviour, extraArgs); } } }
public static object CallMethod(MonoBehaviour monoObject, string methodName, object[] value = null) { object returnValue = null; try { MethodInfo[] methods = monoObject.GetType().GetMethods(); foreach (MethodInfo info in methods) { if (info.Name == methodName) { returnValue = info.Invoke(monoObject, value); // [2] } } return returnValue; } catch(Exception e) { ChirpLog.Error("Unable to Call Method: " + monoObject.GetType().Name + ":" + methodName + ":" + e.Message); ChirpLog.Flush(); return returnValue; } }
/// <summary> /// Validates rigidbody settings. /// </summary> protected List<ValidationResult> CheckRigidbody(MonoBehaviour m, bool isWarning) { List<ValidationResult> result = new List<ValidationResult> (); if (m.GetComponent<Rigidbody2D>() == null) { result.Add (new ValidationResult("Found a " + m.GetType().Name + " but it did not have a rigidbody attached.", isWarning ? MessageType.Warning : MessageType.Info)); } else if (!m.GetComponent<Rigidbody2D>().isKinematic) { result.Add (new ValidationResult("Found a " + m.GetType().Name + " but the rigidboy was not kinematic.", isWarning ? MessageType.Warning : MessageType.Info)); } return result; }
internal static InterpTimedEvent New(UnityEngine.MonoBehaviour receiver, string tag, ref uLink.NetworkMessageInfo info, object[] args, bool immediate) { InterpTimedEvent interpTimedEvent; if (!receiver) { Debug.LogError("receiver is null or has been destroyed", receiver); return(null); } if (!(receiver is IInterpTimedEventReceiver)) { Debug.LogError(string.Concat("receiver of type ", receiver.GetType(), " does not implement IInterpTimedEventReceiver"), receiver); return(null); } if (!InterpTimedEvent.dump.has) { interpTimedEvent = new InterpTimedEvent(); } else { InterpTimedEvent.dumpCount = InterpTimedEvent.dumpCount - 1; interpTimedEvent = InterpTimedEvent.dump.node; InterpTimedEvent.dump = interpTimedEvent.next; interpTimedEvent.next = new InterpTimedEvent.Dir(); interpTimedEvent.prev = new InterpTimedEvent.Dir(); interpTimedEvent.disposed = false; } interpTimedEvent.args = InterpTimedEvent.ArgList.New(args); interpTimedEvent.tag = tag; interpTimedEvent.component = receiver; interpTimedEvent.info = info; if (!immediate) { InterpTimedEvent.queue.Insert(interpTimedEvent); } return(interpTimedEvent); }
internal static InterpTimedEvent New(UnityEngine.MonoBehaviour receiver, string tag, ref uLink.NetworkMessageInfo info, object[] args, bool immediate) { InterpTimedEvent node; if (receiver == null) { Debug.LogError("receiver is null or has been destroyed", receiver); return(null); } if (!(receiver is IInterpTimedEventReceiver)) { Debug.LogError("receiver of type " + receiver.GetType() + " does not implement IInterpTimedEventReceiver", receiver); return(null); } if (dump.has) { dumpCount--; node = dump.node; dump = node.next; node.next = new Dir(); node.prev = new Dir(); node.disposed = false; } else { node = new InterpTimedEvent(); } node.args = ArgList.New(args); node.tag = tag; node.component = receiver; node.info = info; if (!immediate) { queue.Insert(node); } return(node); }
private static string MakeEntryName(MonoBehaviour source, string memberName) { if (source == null || string.IsNullOrEmpty(memberName)) { return null; } string type = source.GetType().Name; return type + "." + memberName; }
/// <summary> /// Convert the specified list of applicable entries to a string array. /// </summary> /// <param name="list">List of entries to convert.</param> /// <param name="selectedSource">MonoBehaviour providing the applicable entries.</param> /// <param name="selectedField">Field to match with list entries.</param> /// <param name="index">Selected list entry.</param> /// <returns>Names of the list entries.</returns> private static string[] GetEntryNames( List<Entry> list, MonoBehaviour selectedSource, string selectedField, out int index) { int selectedEntry = -1; // Fallback is used if no entry matches selected one exactly. // Fallback has same member name and same MonoBehaviour type. int fallbackSelectedEntry = -1; string[] names = new string[list.Count + 1]; for (int i = 0; i < list.Count; ++i) { Entry entry = list[i]; string entryName = MakeEntryName(entry.Target, entry.MemberName); names[i + 1] = entryName; if (selectedEntry == -1 && selectedSource != null) { if (entry.MemberName == selectedField) { if (entry.Target == selectedSource) { selectedEntry = i; } else if (entry.Target.GetType() == selectedSource.GetType()) { fallbackSelectedEntry = i; } } } } if (selectedEntry != -1) { Entry entry = list[selectedEntry]; names[0] = MakeEntryName(entry.Target, entry.MemberName); index = selectedEntry + 1; } else if (fallbackSelectedEntry != -1) { Entry entry = list[fallbackSelectedEntry]; names[0] = MakeEntryName(entry.Target, entry.MemberName); index = fallbackSelectedEntry + 1; } else { names[0] = "<Choose>"; index = 0; } return names; }
public static string FormatListener(MonoBehaviour listener) { return string.Format("{0}/{1}", listener.gameObject.name, listener.GetType().Name.Split('.').Last()); }
private static void AssignVariables(ConfigNode configNode, MonoBehaviour moduleComponent) { IEnumerator enumerator = configNode.values.GetEnumerator(); while (enumerator.MoveNext()) { var current = (ConfigNode.Value) enumerator.Current; if (current == null || current.name == "name" || current.name == "namespace") continue; FieldInfo field = moduleComponent.GetType().GetField(current.name); if (field == null) { Extensions.LogWarning("Could not find the '" + current.name + "' field."); continue; } field.SetValue(moduleComponent, ParseValue(current.value, field)); } }
private bool isUnityEventsNullOrMissing(MonoBehaviour monoBehaviour, bool printError) { targetPropertiesNames.Clear(); FieldInfo[] fieldArray = monoBehaviour.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); for (int i = fieldArray.Length - 1; i >= 0; i--) { FieldInfo field = fieldArray[i]; if (field.FieldType == typeof(UnityEvent) || field.FieldType.IsSubclassOf(typeof(UnityEvent))) { targetPropertiesNames.Add(field.Name); } } if (targetPropertiesNames.Count > 0) { SerializedObject serializedMonoBehaviour = new SerializedObject(monoBehaviour); for (int i = targetPropertiesNames.Count - 1; i >= 0; i--) { string targetProperty = targetPropertiesNames[i]; SerializedProperty property = serializedMonoBehaviour.FindProperty(targetProperty); SerializedProperty propertyRelativeArrray = property.FindPropertyRelative("m_PersistentCalls.m_Calls"); for (int j = propertyRelativeArrray.arraySize - 1; j >= 0; j--) { SerializedProperty arrayElementAtIndex = propertyRelativeArrray.GetArrayElementAtIndex(j); SerializedProperty propertyTarget = arrayElementAtIndex.FindPropertyRelative("m_Target"); if (propertyTarget.objectReferenceValue == null) { if (printError) { appendErrorLine(monoBehaviour.GetType().Name + ": Event object reference is null"); } else { return true; } } SerializedProperty propertyMethodName = arrayElementAtIndex.FindPropertyRelative("m_MethodName"); if (string.IsNullOrEmpty(propertyMethodName.stringValue)) { if (printError) { appendErrorLine(monoBehaviour.GetType().Name + ": Event handler function is not selected"); continue; } else { return true; } } string argumentAssemblyTypeName = arrayElementAtIndex.FindPropertyRelative("m_Arguments").FindPropertyRelative("m_ObjectArgumentAssemblyTypeName").stringValue; System.Type argumentAssemblyType; if (!string.IsNullOrEmpty(argumentAssemblyTypeName)) argumentAssemblyType = System.Type.GetType(argumentAssemblyTypeName, false) ?? typeof(UnityEngine.Object); else argumentAssemblyType = typeof(UnityEngine.Object); UnityEventBase dummyEvent; System.Type propertyTypeName = System.Type.GetType(property.FindPropertyRelative("m_TypeName").stringValue, false); if (propertyTypeName == null) dummyEvent = (UnityEventBase) new UnityEvent(); else dummyEvent = Activator.CreateInstance(propertyTypeName) as UnityEventBase; if (!UnityEventDrawer.IsPersistantListenerValid(dummyEvent, propertyMethodName.stringValue, propertyTarget.objectReferenceValue, (PersistentListenerMode)arrayElementAtIndex.FindPropertyRelative("m_Mode").enumValueIndex, argumentAssemblyType)) { if (printError) { appendErrorLine(monoBehaviour.GetType().Name + ": Event handler function is missing"); } else { return true; } } } } } return false; }
/// <summary> /// Subscribe all the marked rpcs on the supplied component /// </summary> /// <param name="behaviour"></param> public void SubscribeMarkedRPCsOnComponent(MonoBehaviour behaviour) { if (behaviour == this) return; if (behaviour == null) return; var thisType = behaviour.GetType(); if (thisType == typeof(NetworkView)) //speedup return; //get all the methods of the derived type MethodInfo[] methods = thisType.GetMethods( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy ); foreach (MethodInfo method in methods) { var tokens = Attribute.GetCustomAttributes(method, typeof(RpcAttribute), false) as RpcAttribute[]; foreach (var token in tokens) { if (token == null) continue; Action<NetIncomingMessage> del = Delegate.CreateDelegate(typeof(Action<NetIncomingMessage>), behaviour, method, false) as Action<NetIncomingMessage>; if (del != null) SubscribeToRPC(token.rpcId, del); else Debug.LogWarning("The method " + method.Name + " for type " + method.DeclaringType.Name + " does not match the RPC delegate of Action<NetIncomingMessage>, but is marked to process RPC's. Please either fix this method, or remove the attribute", behaviour); } } }
/// <summary>Error log is marked with a red error symbol.</summary> /// <param name="methodName">The name of the method in which this is used.</param> /// <param name="mb">The monobehaviour from which this was called.</param> /// <param name="errorMessage">The message to display.</param> public static void Error(this MonoBehaviour mb, string errorMessage, [System.Runtime.CompilerServices.CallerMemberName] string methodName = default) { Debug.LogError(string.Format("{0}.{1}.{2}: {3}", mb.ObjectPath(), mb.GetType().Name, methodName, errorMessage)); }
/// <summary>Temp logging is like debug but in green. Used for logs during actual debugging. Dispose of after use.</summary> /// <param name="methodName">The name of the method in which this is used.</param> /// <param name="mb">The monobehaviour from which this was called.</param> /// <param name="debugMessage">The message to display.</param> public static void Temp(this MonoBehaviour mb, string debugMessage, [System.Runtime.CompilerServices.CallerMemberName] string methodName = default) { Debug.Log(string.Format("<color=green>{0}.{1}.{2}: {3}</color>", mb.ObjectPath(), mb.GetType().Name, methodName, debugMessage)); }
public static object GetFieldValue(MonoBehaviour monoObject, string fieldName) { try { BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; FieldInfo fieldInfo = monoObject.GetType().GetField(fieldName,bindingFlags); //fieldInfo.SetValue(monoObject,value); return fieldInfo.GetValue(monoObject); //return true; } catch(Exception e) { ChirpLog.Error( "Unable to get Value: " + monoObject.GetType().Name + ":" + fieldName + ":" + e.Message); ChirpLog.Flush(); return 0; } }
internal void SubscribeSynchronizedFields(MonoBehaviour behaviour) { if (behaviour == this) return; if (behaviour == null) return; var thisType = behaviour.GetType(); if (thisType == typeof(NetworkView)) //speedup return; //get all the methods of the derived type var fields = thisType.GetFields( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy ).OrderBy(f => f.Name); foreach (FieldInfo field in fields) { Type fieldType = field.FieldType; if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(SynchronizedField<>)) { var instance = fieldType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(NetworkView) }, null).Invoke(new object[] { this }); field.SetValue(behaviour, instance); } } }