- Home /
Question by
noswadecyrb · Nov 24, 2011 at 09:34 PM ·
instantiatetransformprefabstaticmenuitem
How do I instantiate a Prefab using a MenuItem?
Main problem hear is that the a MenuItem Method has to be static. But if you declare a Transform variable as a static variable then you you can't access it in the editor. Then you can't assign a Prefab to it.
e.g.
static var thingToClone : Transform;
@MenuItem("MyMenu/Thingy")
static function funky {
var clone = Transform;
clone = instantiate(thingToClone, Vector3(0,0,0), Quaternion(0,0,0,0));
}
From other questions I think I should us a singleton, but I don't know how to implement that into my code.
Comment
Answer by SkaredCreations · Nov 25, 2011 at 10:16 AM
Since it is a MenuItem you could use Selection.activeObject to retrieve the currently selected prefab from your project view and instantiate it:
@MenuItem ("MyMenu/Thingy")
static function funky () {
if (EditorUtility.IsPersistent(Selection.activeObject)) {
var newGO : GameObject = Selection.activeObject;
Instantiate(newGO, Vector3.zero, Quaternion.identity);
}
}
Else if you know exactly what is the prefab you want to instantiate, you could put the prefab in the Resources folder and use it:
@MenuItem ("MyMenu/Thingy")
static function funky () {
var newGO : GameObject = Resources.Load("Cube");
Instantiate(newGO, Vector3.zero, Quaternion.identity);
}