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!

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.

umm, what about using the Awake() method from Monobehaviour? It’s useful for initialization like the one you’re going to do.