Can a prefab be written in code?

I don't mean instantiated, but can you actually create a (say, C#, although I'm not fussy :-) class that represents a Prefab? And if so, what would that class look like?

All the explanations that I've seen involve creating prefabs using the IDE.

Thanks for any insights!

3 Answers

3

Well, you can certainly do this in code. Consider this psuedo code for example:

public GameObject CreateMilkBottle()
{
    var prefab = new GameObject("Milkbottle");
    var milk = prefab.AddComponent<MilkContainer>();
    milk.Capacity = 300;
    var meshFilter = prefab.AddComponet<MeshFilter>();
    meshFilter.mesh = loadmesh();
    prefab.AddComponent<MeshRenderer>();
    prefab.AddComponent<BoxCollider>();
    // etc
    return prefab;
}

If you really want it on disk, try this: http://unity3d.com/support/documentation/ScriptReference/AssetDatabase.CreateAsset.html

have a look at PrefabUtility.CreateEmptyPrefab
that creates things like prefabs programatically. :slight_smile: