You will have to mark you object dirty so it will be saved when hitting CTRL+S
EditorUtility.SetDirty
You can use SetDirty when you want to modify an object without creating an undo entry, but still ensure the change is registered and not lost. If the object is part of a Scene, the Scene is marked dirty.
public class MyBehaviour : MonoBehaviour
{
#if UNITY_EDITOR
private void OnValidate()
{
if (!this.name.Contains("_"))
{
this.name = $"{this.name}_{this.GenUID()}";
EditorUtility.SetDirty(this);
}
}
#endif
}
Also note
If the object may be part of a Prefab instance, you additionally need to call PrefabUtility.RecordPrefabInstancePropertyModifications
to ensure a Prefab override is created.
And if you want to also support Undo/Redo
If you do want to support undo, you should not call SetDirty
but rather use Undo.RecordObject
prior to making changes to an object, since this will both mark the object as dirty (or the object's Scene if it is part of a Scene) and provide an undo entry in the editor. You should still also call PrefabUtility.RecordPrefabInstancePropertyModifications
if the object may be part of a Prefab instance.