- Home /
Using attributes to store data at edit time
Say I have an attribute that I add to a field. I want this attribute to store a Vector2 which is the position of this field in my custom editor. It works okay while in edit time, but seems to deserialise on Unity close/play. Is there a way to have attributes save their data, that is not declared in a constructor? Thank you!
Answer by brunocoimbra · Oct 06, 2017 at 12:20 PM
None by default, but the monoBehaviour or ScriptableObject that holds the attribute can.
(...)
public class FieldMarker : Attribute
{
public string positionProperty;
public FieldInputType displayType;
(...)
public FieldMarker(FieldInputType _diplayType, string _positionProperty)
{
//assign values.
}
}
(...)
Then in your MonoBehaviour or ScriptableObject:
(...)
public class Test : MonoBehaviour
{
[SerializeField] private Vector2 position;
[SerializeField, FieldMarker(FieldInputType.Value, "position")] private float myVar;
}
Other option would be to create your own custom way to save and load data between Edit, Close and Play, but it really depends on what you are trying to do.
So are you proposing that I store the name of the position (which is in the class that this attribute is added to) and then pass that through to the attribute? Would I then have to access the position via reflection in the attribute? Darn about the fact attributes can't hold non-initialised data :/
If you are creating a Custom Editor for the class, you can access with serializedObject.FindProperty(positionPropertyName).vector2Value, if not, then yes, by reflection.
Also, it's not that "attributes can't hold non-initialized data", it is just that you never told then to do that (what would require a custom way to save and load it, as I told you before). The only reason that $$anonymous$$onoBehaviour and ScriptableObject can do that by default, is because Unity already did that work for us.
Okay cool, thank you :) Not the way I wanted it to work out, but it's not infeasible!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Custom attribute not respecting property's PropertyDrawer 0 Answers
EditorGUI.PrefixLabel got truncated 0 Answers
Editor Scripting: change selected objects layer with button press 0 Answers