How do I programmatically assign a GameObject to a prefab?

When importing a mesh, I want to automatically create a prefab for that mesh, and assign that mesh to the new prefab. I have something like this:

public class MyAssetPostprocessor : AssetPostprocessor
    public void OnPostprocessModel(GameObject gameObject)
        if (assetPath.EndsWith("_model.fbx"))
            string prefabPath = assetPath.Replace("_model.fbx", ".prefab");
            Object prefab = EditorUtility.CreateEmptyPrefab(prefabPath);
            // prefab.AddGameObject(gameObject); ?

But I don't know how to add the mesh to the prefab. In the editor, I can drag-and-drop it in the project window. How do I do this programmatically?

This is a snippet from the code I use to create prefabs from a group of selected objects:

[MenuItem ("My Project/Create Simple Prefab")]
static void DoCreateSimplePrefab()
	Transform[] transforms = Selection.transforms;
	foreach (Transform t in transforms) {
		Object prefab = EditorUtility.CreateEmptyPrefab("Assets/Temporary/"".prefab");
		EditorUtility.ReplacePrefab(t.gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab);

You may want to try with EditorUtility.ReplacePrefab, althought caveat emptor: I've only used it at editor time, not in the asset post-processor.

You should now be using PrefabUtility, not EditorUtility for all prefab operations. Not only does it have a method for creating empty prefabs but it also has a method to create prefabs from existing GameObjects:

GameObject prefab = PrefabUtility.CreatePrefab("Assets/Whatever.prefab", (GameObject)Selection.object, ReplacePrefabOptions.ReplaceNameBased);

Use CreateEmptyPrefab to prepare your prefab asset. Then construct your desired GameObject as you would like it to be ingame. Finally use ReplacePrefab to store your GameObject in your prefab and Destroy the original GameObject if you don't want it in the scene.

You can use ReplacePrefabOptions = ReplaceNameBased without destroying scene object problem.

    Object prefab = EditorUtility.CreateEmptyPrefab("Assets/test1.prefab");
    EditorUtility.ReplacePrefab(importedObject, prefab, ReplacePrefabOptions.ReplaceNameBased);

My personal favourite:

var selection = Selection.gameObjects;

    for (int i = 0; i < selection.Length; i++)
      PrefabUtility.CreatePrefab("Assets/" + + ".prefab", selection*, ReplacePrefabOptions.ConnectToPrefab);*_

Objects in scene are then connected to prefabs and turn blue.

Use Prefab in your Game Here is the tutorial for that . Unity3D Notes: Instantiate Prefab in Your Game Tutorial . Here is demo and code for Prefab instantiate so download and try to undestand i hope u will get the solution …