private void InjectMemberFromUnitySearchMethod(MonoBehaviour script, MemberInfo memberInfo, SearchMethods searchMethod, bool isOptional) { Type componentType = ReflectionUtils.GetTypeOfFieldOrProperty(script, memberInfo); // For testing, searching in the scene hierarchy using a Unity method can be simulated to return a mockup for a component. object component = GetComponentFromUnitySearchMethodMockups(script, searchMethod, componentType); if (component == null) { // No mockup found, thus use the real Unity search method. component = UniInjectUtils.InvokeUnitySearchMethod(script, searchMethod, componentType); } if (component != null) { if (memberInfo is FieldInfo) { (memberInfo as FieldInfo).SetValue(script, component); } else if (memberInfo is PropertyInfo) { (memberInfo as PropertyInfo).SetValue(script, component); } else { throw new Exception($"Cannot inject member {script.name}.{memberInfo}." + $" Only Fields and Properties are supported for component injection via Unity methods."); } } else if (!isOptional) { throw new Exception($"Cannot inject member {script.name}.{memberInfo.Name}." + $" No component of type {componentType} found using method {searchMethod}"); } }
private static int CheckInjectableFromUnitySearchMethod(MonoBehaviour script, Type type, InjectionData injectionData) { if (injectionData.InjectionKeys.Length > 1) { // If there are multiple keys, then it must be for a method or constructor with multiple parameters LogErrorCannotBeInjected($"The search method {injectionData.searchMethod} can only be used on a field or property.", script, type, injectionData.MemberInfo); return(1); } object injectionKey = injectionData.InjectionKeys[0]; if (!(injectionKey is Type)) { LogErrorCannotBeInjected($"The search method {injectionData.searchMethod} can not be used with a custom key.", script, type, injectionData.MemberInfo); return(1); } Type componentType = injectionKey as Type; UnityEngine.Object searchResult = UniInjectUtils.InvokeUnitySearchMethod(script, injectionData.searchMethod, componentType); if (searchResult == null) { LogErrorCannotBeInjected($"No instance of {componentType} found using {injectionData.searchMethod}.", script, type, injectionData.MemberInfo); return(1); } return(0); }