/// <summary>
        /// Initializes reference to components or GameObject on fields that use the [ComponentRef] attribute.
        /// </summary>
        public static void InitComponentRefs(this Component _Component)
        {
            foreach (FieldInfo fieldInfo in _Component.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                // If the current field doesn't use the ComponentRef attribute, skip this field
                if (!Attribute.IsDefined(fieldInfo, typeof(ComponentRefAttribute)))
                {
                    continue;
                }

                // If the current field's value is already set, skip this field
                if (fieldInfo.GetValue(_Component) != null)
                {
                    continue;
                }

                ComponentRefAttribute attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(ComponentRefAttribute)) as ComponentRefAttribute;
                // Find a component or GameObject reference depending on the [ComponentRef] attribute settings
                Object reference = FindComponentRef(_Component, fieldInfo.FieldType, attribute.Scope, attribute.RefObjectName);

                // Replace the field value if applicable
                if (reference != null)
                {
                    fieldInfo.SetValue(_Component, reference);
                }
            }
        }
Beispiel #2
0
        public override void OnGUI(Rect _Position, SerializedProperty _Property, GUIContent _Label)
        {
            if (_Property.hasMultipleDifferentValues)
            {
                EditorGUI.PropertyField(_Position, _Property);
                return;
            }

            if (_Property.propertyType == SerializedPropertyType.ObjectReference)
            {
                Component propertyContainer = _Property.serializedObject.targetObject as Component;
                if (propertyContainer != null)
                {
                    Type propertyType = EditorHelpers.GetPropertyType(_Property);
                    if (propertyType != null && propertyType.IsSubclassOf(typeof(Component)) || propertyType == typeof(GameObject))
                    {
                        if (_Property.objectReferenceValue == null)
                        {
                            ComponentRefAttribute attr = attribute as ComponentRefAttribute;
                            _Property.objectReferenceValue = ComponentExtension.FindComponentRef(propertyContainer, propertyType, attr.Scope, attr.RefObjectName);
                        }
                    }
                }
            }

            EditorGUI.PropertyField(_Position, _Property);
        }