- Home /
Do I need to use SetDirty in my editors if I'm using SerializedProperties?
I've been making tons of custom editors. At first I started using target only as SPs was a pain to work with - but then I realized the benefits SPs give, and managed to get along.
But at no point of time, I used SetDirty
- I still see it in some editor scripts, but don't really know why they ever need it.
The docs says that you need to SetDirty
on a prefab for ex, if you change a value in one of its MonoBehavoiurs
for it to be saved to disk.
I haven't found any need to do that. I could change a value in a prefab's MB, enter/exit play mode, exit/re-enter Unity - the value is still there.
So what's the use of SetDirty, and when do I ever need it? Is this some legacy thing that was used when dealing with target
directly?
Thanks!
Answer by MakeCodeNow · Feb 17, 2014 at 02:44 AM
SetDirty is needed if you change values without using SerializedProperty. Pretty much anywhere you'd need to add a manual call to Undo.Record, you'd want to call SetDirty.
As an example, I have some ScriptableObject subclasses with accessor properties that modify private, serialzied members. I have to use SetDirty inside these accessors.
Thanks for your answer.
Indeed, with SPs I didn't seem to need to call SetDirty. But in the doc they mentioned that internally they do call SetDirty for us, so why would they ever expose it to us then?
Well, I made some tests. First a prefab with an $$anonymous$$B, I modified some of its values via its default inspector, enter/exit play mode, restarted unity, the value persisted. no need for SetDirty, But then @Jamora mentioned to me that that's because I was modifying the value via the defauilt inspector. So I tried modifying it directly (just like in the doc example) - it persisted after I enter/exit play mode, but not after a Unity restart! "because it was only loaded in memory, not saved to disk" - Jamora. I tried SetDirty and indeed it did persist after a Unity restart.
"Pretty much anywhere you'd need to add a manual call to Undo" - You mean Undo.Record? or any of the undo methods? How about Undo.DestroyObjectImmediate
? how would I SetDirty after that? (Since the object is gone, destroyed?)
Yes, I meant Undo.Record. I'll update the answer with that.
Your answer
Follow this Question
Related Questions
Dynamic serialized fields based on enum 0 Answers
How do I associate my custom object for the serializedProperty objectReferenceValue 1 Answer
How to initialize array[][] via SerializedProperty? 1 Answer
How to work with custom class (ScriptableObject) SerializedProperty? 1 Answer
What would be the best way to go about loading and saving a Serializable object in JSON with Unity? 0 Answers