- Home /
How to programmatically break prefab instance upon adding to hierachy
I have some prefabs that I use for level design. I'd like to "Break Prefab Instance" programmatically as soon as I drop the prefab into the scene. Is there an easy way to do this?
FYI, I want to do this because these particular prefabs are used as starting points for different level items and get heavily modified after dropping them into the scene. I need to ever "Apply" these changes.
-Jeff
Answer by Bunny83 · Sep 27, 2012 at 11:12 AM
Just use PrefabUtility.DisconnectPrefabInstance, but keep in mind it can only be used in an editor script or you have to surround the call with pre-processor tags `#if UNITY_EDITOR`
Here's an example that should work:
// AutoBreakPrefabConnection.cs
using UnityEngine;
[ExecuteInEditMode]
public class AutoBreakPrefabConnection : MonoBehaviour
{
void Start()
{
#if UNITY_EDITOR
PrefabUtility.DisconnectPrefabInstance(gameObject);
#endif
DestroyImmediate(this); // Remove this script
}
}
I haven't tested it yet, but in theory you would attach this script to the prefab itself (not to an instance of the prefab). When the prefab gets instantiated, it will run the Start method, it will beak the prefab connection and remove the script from the instance.
Great, thanks. I'll test this and mark as answer once it's confirmed to work.
Finally got around to testing this. Works great. Only had to make one small change. Need to add
using UnityEditor;
PrefabUtility is part of that namespace.
You're going to want to add #if UNITY_EDITOR around the 'using UnityEditor' as well, or just write UnityEditor.PrefabUtility... otherwise whenever you try to make a build it will fail because the editor doesnt' exist.
Unfortunately DisconnectPrefabInstance()
is deprecated. From documentation: "Deprecated. As of 2018.3 this method does nothing.". Probably UnpackPrefabInstance()
replaced this one.
Your answer

Follow this Question
Related Questions
How to find the prefab base of a Prefab Variant through code? 1 Answer
Reinitialize prefab 0 Answers
Create a Prefab from imported Assets automatically 0 Answers
Pressing Apply Breaks Prefab 1 Answer