GameObject with AssetDatabase.CreateAsset problem

I want to create a prefab programmatically, something like the following:

GameObject MyPrefab = new GameObject();
MyPrefab.active = false;
MyPrefab.AddComponent(typeof(MyComponent));

AssetDatabase.CreateAsset(MyPrefab, "My_new_prefab.prefab");

The prefab gets created, and everything looks like it’s working. However, there is an error in the console:

“Cleaned up leaked objects…”
MyComponent has been leaked 1 times.

After I save and restart Unity, the new prefab has no components and doesn’t have a transform either.

How do I create prefabs with MonoBehaviours from inside custom editor scripts?

Hey cannon,

have you nailed this one anyhow?

Hi Rodriga,

The rest of our research on this connects to this thread:
http://forum.unity3d.com/viewtopic.php?p=238785#238785

Basically, no.

With the calls we were using, the prefab was being created with only a pointer/reference to the current in-scene game object. The pointer was of course no longer valid the next time we ran Unity; the game object was not actually persisted to the prefab file.

If ever you find an answer I’d be curious to know, but for now we’ve handled our requirements in a different way.

did you ensure that you ran the whole code in edit mode not game mode? game mode changes are never persistent in any way

Thanks, already seen that one.

alright, i’ll give you a shout in this case.

yeah, i’m in the editor for sure.

You can use something like this:

GameObject animHolder = new GameObject("pf_anim_" + animClip.name);
AnimClipHolderMonobeh animHolderMonobeh = animHolder.AddComponent<AnimClipHolderMonobeh>();
animHolder.active = false;//!!!

//some customizing
//        animHolderMonobeh.animClip = animClip;
//        animHolderMonobeh.animSpeed = 1f;
//        animHolderMonobeh.moveSpeed = 4f;

string newPrefabName = pathToAnimationPrefabs + animHolder.name + ".prefab";
Object newPrefab = EditorUtility.CreateEmptyPrefab(newPrefabName);
EditorUtility.ReplacePrefab(animHolder, newPrefab, ReplacePrefabOptions.ConnectToPrefab);

I haven’t seen those calls before. They perform nicely, thanks :smile: .

Hey Fer,

I’ve been using the exact same code as you could see in this thread.

The issue for me though is that I’m creating the prefab out the asset bundle so all references are empty once I load that saved prefab.

I’ve got an idea on recreating the prefab internal hierarchy based on the transforms, will see how that goes.