x


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.

more ▼

asked Nov 24 '11 at 09:34 PM

noswadecyrb gravatar image

noswadecyrb
1 3 3 4

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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);
}
more ▼

answered Nov 25 '11 at 10:16 AM

SkaredCreations gravatar image

SkaredCreations
136 2

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1672
x1279
x1254
x276
x14

asked: Nov 24 '11 at 09:34 PM

Seen: 568 times

Last Updated: Nov 25 '11 at 10:16 AM