- Home /
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?
I know I could assign those fields on the Awake() function, but I'd like to avoid writing those lines in every class with this kind of fields
Answer by Bunny83 · Jan 05, 2016 at 02:46 PM
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 ^^.
ps: I haven't yet seen the "DidReloadScript" attribute. It probably becomes quite useful in the future. I still use the InitializeOnLoad attribute for better backwards compatibility. However if you have problems with InitializeOnLoad you might want to remove the whole update delegate thing and try DidReloadScript on the DoSelfAssign method.
I'm not sure when and from which thread the DidReloadScript callback gets called exactly. So you might need to do some pionier work i guess ^^.
Your answer
Follow this Question
Related Questions
Creating object properties dynamically in unity javascript. 2 Answers
Is RequireComponent[typeof(CustomScript)] possible? 2 Answers
[OnSerialize] and other events doesn't work 0 Answers
Is it possible to add an icon to indicate there is an editor tooltip decorating a variable? 0 Answers
Custom [Require*] attribute 2 Answers