- Home /
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!
Answer by Statement · Mar 22, 2011 at 11:23 PM
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;
}
I guess I meant something like ...
public class $$anonymous$$yPrefab : GameObject {
}
If (and that's a big if :-) I understand this page -- http://unity3d.com/support/documentation/$$anonymous$$anual/Instantiating%20Prefabs.html -- correctly, then Create$$anonymous$$ilkBottle() isn't really creating a prefab, but just individual unrelated GameObjects. Otherwise it would be using Instantiate() ... I think ...
Having said that, what you wrote was really instructive as it solved another problem that I hadn't even asked yet. How did you do that? :-)
No, you can't create subclasses of GameObject because the class is sealed, meaning the designers of the class didn't want/expect people to subclass it. The creation of the prefab is just in the code above, although it might not seem that clear. A prefab is basically a serialized instance of a game object. It serialize scripts and values. Prefab just means "prefabricated". It's there to save you doing just what the above code does. What is the intent of this? Perhaps there exist another feature in Unity that does the job? Instantiate just create a game object from a preset like the code.
Answer by DaveA · Mar 23, 2011 at 12:47 AM
If you really want it on disk, try this: http://unity3d.com/support/documentation/ScriptReference/AssetDatabase.CreateAsset.html
Answer by MountDoomTeam · Sep 22, 2012 at 02:54 PM
have a look at PrefabUtility.CreateEmptyPrefab that creates things like prefabs programatically. :)