- Home /
How to detect if Prefab was added to the scene in Edit Mode?
I've made a custom editor and want the Prefab which contains the custom editor script to run some code when it detects it has been added to the scene in Edit Mode. I only want it to run the code once when it's added. I can detect Edit Mode using:
if (!Application.isPlaying)
but haven't been able to detect the adding-to-the-scene part.
Answer by darksider2000 · May 14, 2020 at 11:20 PM
Hi there,
You should look into ExecuteInEditMode.
That page has everything you need to know about running code while in the editor.
As for running it when a prefab is instantiated in the scene the simplest way I know of is gameObject.scene, which returns the scene with all of its properties. I would just check gameObject.scene.name to see if it's in the scene or not.
ExecuteInEdit$$anonymous$$ode is useful, thanks for that. However, I'm still not able to detect when a prefab was added to the scene (or even if a prefab was selected in the hierarchy).
If I use
private void OnEnable()
{
if (script.gameObject.scene.IsValid())
{
//Selected in hierarchy/prefab mode
}
else {
//Selected in project window
}
}
I can detect when the prefab is selected in the project window but not specifically in the hierarchy since a selection in prefab mode gives the same result as in the hierarchy.
Your answer
Follow this Question
Related Questions
Automatically increment an integer field in a bunch of prefab gameobjects in the unity editor. 0 Answers
Using a custom editor script with a prefab instance causes my variables to reset on Play 3 Answers
How can I stop a stopwatch using "on trigger enter"? 2 Answers
Rotatearaound a moving object 1 Answer
delay "after mouseclick" 0 Answers