- Home /
Execute code once when a prefab is placed into the scene?
Hello guys!
Is it possible to run code only once when a prefab is dragged and dropped into the scene for the first time only?
I have a NPC prefab, this prefab has a script that contains two strings, a name and a surname.
I created a function that can be activated via Context Menu that assigns a random name and surname to the NPC.
Everytime I place the NPC Prefab in the scene I have to select it, right click for the context menu and activate the function myself. I was wondering if there is a way to automatically call that function whenever the prefab is instantiated in the scene. That would save me a lot of time and it would prevent me from forgetting about assigning names!
like @Rechronicle said, you can use the awake method on a prefab's monobehaviour, which will execute only once when when the gameobject is initialised
Answer by Rechronicle · Oct 10, 2021 at 03:43 PM
umm, what about using the Awake() method from Monobehaviour? It's useful for initialization like the one you're going to do.
Answer by luisquid · Oct 15, 2021 at 07:59 PM
Have you checked the OnHierarchyChange method?
Actions that trigger this message include creating, renaming, reparenting, or destroying objects in the current hierarchy, as well as loading, unloading, renaming, or reordering loaded Scenes
Maybe that could be useful on detecting when you add your object to the scene and run your function from that.
Your answer
![](https://koobas.hobune.stream/wayback/20220613044025im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Play Unity Editor from VSCode? 0 Answers
How to run script in editor 1 Answer
SceneView.onSceneGUIDelegate GUI sorting problem 1 Answer
EditorGUI.PrefixLabel got truncated 0 Answers
How to use an Editor script? 0 Answers