Self-assigning field in class

I’ve created an attribute I put on fields of a certain class to allow self-assignment of other components attached to itself. Here’s the code :

SelfAssignAttribute.cs

using System;
using UnityEngine;

[AttributeUsage(AttributeTargets.Field)]
public class SelfAssignAttribute : PropertyAttribute 
{
    public SelfAssignAttribute() { }
}

SelfAssigningAttributeEditor.cs

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(SelfAssignAttribute)]
public class SelfAssignAttributeEditor : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) 
    {
        //This is a short version stripped of validation to show the general idea of the attribute
        if(property.objectReferenceValue == null) 
        {
            MonoBehaviour mb = (property.serializedObject.targetObject as MonoBehaviour);
            property.objectReferenceValue = mb.transform.GetComponent(fieldInfo.FieldType);
        }
    }
}

It sure works as intended, but only when OnInspectorGUI is called on said GameObject which fields are tag with [SelfAssignAttribute]. The problem is, I’d like this assignment to occur when scripts are being rebuilt.

Is there a better way than scanning every object in the scene using [UnityEditor.Callbacks.DidReloadScript] in every scene of the project?

Unfortunately there’s no way around your “scanning every object”. Keep in mind that an attribute instance is part of the class, not part of a particular instance of that class. That means just your attribute class alone doesn’t know about any instances of classes that might have fields with that attribute attached.

Your propertydrawer solution is quite nice, but as you figured out the code only runs when the object is inspected. The inspector is the connection between object instance and your static attribute data.

So the best way is probably to use a seperate script that has an InitializeOnLoadAttribute which scans all MonoBehaviour instances for your attribute and perform that action from the update delegate to ensure everything is loaded and deserialized.

Something like that:

using System;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using System.Linq;

[AttributeUsage(AttributeTargets.Field)]
public class SelfAssignAttribute : Attribute
{
    public Type type = null;
}

[AttributeUsage(AttributeTargets.Field)]
public class ManagerAttribute : SelfAssignAttribute
{
}

[InitializeOnLoad]
public class SelfAssignHelper
{
    static SelfAssignHelper()
    {
        EditorApplication.update += OnUpdate;
    }
    static void OnUpdate()
    {
        EditorApplication.update -= OnUpdate; // unsubscribe after first call
        DoSelfAssign();
    }
    [MenuItem("Tools/PerformSelfAssign")]
    static void DoSelfAssign()
    {
        var objs = Resources.FindObjectsOfTypeAll<MonoBehaviour>();
        foreach (var obj in objs)
        {
            if (obj == null)
                continue;
            var type = obj.GetType();
            var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
            foreach(var field in fields)
            {
                var attr = field.GetCustomAttributes(true)
                    .Where(a=>a is SelfAssignAttribute)
                    .Cast<SelfAssignAttribute>()
                    .FirstOrDefault();
                if (attr != null && field.GetValue(obj) != null)
                {
                    var t = field.FieldType;
                    if (attr.type != null)
                        t = attr.type;
                    var val = obj.GetComponent(t);
                    if (val == null && attr is ManagerAttribute)
                        val = Resources.FindObjectsOfTypeAll(t).FirstOrDefault() as Component;
                    if (field.IsStatic)
                        field.SetValue(null, val);
                    else
                        field.SetValue(obj, val);
                }
            }
        }
    }
}

I also scan static fields as well. This usually makes no sense, but for singleton references it might be useful. Keep in mind that if multiple instances of a class exist, only the last one will persist.

I added an optional “type” parameter to the attribute. That allows you to also search for more concrete types if the field type is a base type. You probably never need this but i think it might be useful.

I also added a subclass attribute which allows you to initialize “manager” references. This simply searches the whole scene if GetComponent doesn’t return anything. That allows you to initialize references to managers, no matter where they are stored.

Finally i also create a menuitem to manually trigger the field check at any time you like.

That would probably be my approach ^^.

Note: I haven’t tested that class yet, so feel free to report any errors if you want to use it ^^.