var prefab = PrefabUtility.CreateEmptyPrefab(path + "/test.prefab") as GameObject;
prefab.AddComponent<TestComponent>();
The test.prefab is created correctly in the path. However, but the reference to the instance prefab is null. Why is this so? How can I then hold on to the reference of the Prefab and add a component to it?
The following documentation demonstrates how to achieve this by replacing the contents of the prefab after creation:
For example, in your scenario the following may be of use:
// Create and prepare your game object.
GameObject go = new GameObject("Name of GO");
go.AddComponent<TestComponent>();
// Create empty prefab and replace with content of `go`.
Object prefab = PrefabUtility.CreateEmptyPrefab(path + "/test.prefab");
PrefabUtility.ReplacePrefab(go, prefab, ReplacePrefabOptions.ConnectToPrefab);
Another solution is to use the PrefabUtility.CreatePrefab function which is slightly simpler than above:
// Create and prepare your game object.
GameObject go = new GameObject("Name of GO");
go.AddComponent<TestComponent>();
// Create prefab from object.
PrefabUtility.CreatePrefab(path + "/test.prefab", go, ReplacePrefabOptions.ConnectToPrefab);
When manual modifications are made to your prefab (following creation) be sure to use EditorUtility.SetDirty so that such changes are persisted.