Is it possible for Attribute fields to be serialized?

Is it possible for the fields inside a class that is inherited from Attribute to be serialized?

using UnityEngine;
using UnityEditor;

public class Test : MonoBehaviour
{
	[MyAttribute]
	public string randomVariable;
}

public class MyAttribute : PropertyAttribute
{
	public Object targetObjectIWantToSerialize;
}

[CustomPropertyDrawer(typeof(MyAttribute))]
public class MyAttributeDrawer : PropertyDrawer
{
	MyAttribute myAttributeInstance;
	const bool allowSceneObjects = true;
	
	public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
	{
		if(myAttributeInstance == null)
			myAttributeInstance = attribute as MyAttribute;
		
		myAttributeInstance.targetObjectIWantToSerialize = EditorGUI.ObjectField(
			position,
			"Target Object I wanna serialize",
			myAttributeInstance.targetObjectIWantToSerialize,
			typeof(Object),
			allowSceneObjects
		);
	} 
}

What will happen here is, when you assign something to “targetObjectIWantToSerialize” through Inspector, then select other objects, that will unload the current Inspector. The ‘targetObjectIWantToSerialize’ will go empty again

You can just add the SerializeField attribute on top of your own attribute, like:

[MyAttribute, SerializeField]
public string randomVariable;

No, that’s not possible. Attributes are static metadata that is compiled into the assembly. Attributes can only contain pure static data that is available at compile time. While attribute classes may contain other fields at runtime, the information stored in an attribute inside the assembly must be static data.

In essence attributes are instances which are stored directly into the assembly byte code when the assembly is compiled. That’s why they can only contain information that does not change. So mainly value types or System.Type references which themselfs are metadata. Attribute instance only exists once per usage. So attributes are bound to the type they are used in. In your case your “Test” class. So the attribute instance is static data shipped with the Test class and is not related to an instance of your Test class. So all Test classes share the same attribute instance. Again, it’s just additional metadata inside the reflection system.

So if you want to assign UnityEngine.Object instances in the inspector, you have to serialize this information in actual fields of the serialized class. The inspector works soley on the compiled code and instances in memory / stored on disk.