Stop Unity from altering non-instanced prefabs at runtime?

I’ve noticed that Unity will sometimes permanently alter a prefab that doesn’t appear in the scene.

Usually, this is because there’s a bug; something is referencing something it shouldn’t.
But I find it odd that Unity will let you introduce a bug that can wipe whole swaths of data in prefab files.
I can’t think of too many workflows where you would want this behavior.

If a script tries to change a prefab reference file instead of an instance of a prefab, I’d really want an error.

Is there a way to “lock” prefabs so the permanent reference on your hard drive can’t be changed by a script?

You can always fix it from version control. It’s a pain, but with proper version control data is seldom lost permanently. As an extra precaution I always scan my commits before uploading them to the repo. If there are any prefabs that I wasn’t working on changed, I simply discard the change.

Having scripting access to be able to modify prefabs in the editor is useful.

I like to be able to add stuff to prefabs. For instance I use it to run a custom script on my instantiated objects from prefabs before any Awake call is called on any other. This is useful if I need to parent a new instance before it’s created.

You could avoid modifying objects that are prefabs by default. If you have a script that allows drag and drop of a Gameobject from your assets, don’t add things, or modify it. Always instantiate first.

Furthermore, unity has a parameter on the EditorGUI.ObjectField drawer that controls if ‘sceneObjects’ are allowed or not ( a scene object being something that is not a prefab). I have written PropertyDrawers that explicitly use this to lock out scene objects to ensure that the object is a prefab… vice versa, because you can test if an object is a prefab in editor, you can validate that its NOT a prefab as well through a similarly written PropertyDrawer. Thusly allowing you to lock out the adding of prefabs, or sceneobjects, to fields that do get modified before duplication through Instantiate.