Saving changes in a component modified by an editor script

I need to give a few objects an unique id. Instead of doing it by hand I wrote an editor script.

The script works perfectly, but it doesnt save the changes even after i save the scene (it reverts the id to 0 when i enter play mode)

Here’s the script (the relevant part) :

public bool assignedID = false;
public string id = "";

void Awake()
{

    if (Application.isPlaying) return;

    if (!assignedID)
    {

        // these work perfectly, ignore them
        assignedID = true;
        id = GetUnusedID();



        // none of this works
        EditorUtility.SetDirty(this);
        EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
        EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());

    }

}

After 20 years of trial and error I seem to have fixed it. You have to break the prefab instance or it will keep resetting.

    PrefabUtility.DisconnectPrefabInstance(this);

There’s probably a better workaround but this one worked for me.

Had similar problem, changed fonts in editor but no saving. Helped this topic:

you need to set dirty before making a change