x


Change prefab before instantiation

Is it possible (or sensible) to change a "prefab" in a script before passing it to instantiate?

For example, something like the following:

// assigned in the editor
var prefab : GameObject;

function Start() {
    prefab.GetComponent(FooComponent).ownerObject = this.gameObject;
}

function Foo() {
    var newObject : GameObject = Instantiate(prefab, Vector3.zero, Quaternion.identity);

    // now don't have to do this - a saving if instantiating many objects of this type
    //newObject.GetComponent(FooComponent).ownerObject = this.gameObject;
}

I tried this with Network.Instantiate, and it broke horribly and silently (at which I'm not surprised). Now I'm wondering if this would work with the standard Instantiate function?

more ▼

asked Jan 02 '11 at 04:56 PM

Matthew A gravatar image

Matthew A
502 7 9 18

I have actually never tried to do so, but why not change it after you have initialised it?

Jan 02 '11 at 05:01 PM Ejlersen

Well, if this is a script in my player object that fires bullets, I was hoping to set the owner of every bullet instantiated by this player by altering the prefab once for each player, instead of setting it after every instantiation of a bullet on every player.

Jan 03 '11 at 12:22 PM Matthew A
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

It does work, but it has the consequence that the altered Prefab will remain changed when you leave play mode. You're literally altering the Prefab, so the changes persist beyond runtime.

more ▼

answered Jan 02 '11 at 06:42 PM

d3coy gravatar image

d3coy
252 1 1 10

Ok, thanks. It's interesting to know that unity still regards it as a prefab rather than a GameObject as its type indicates. Oh well.

Jan 03 '11 at 12:24 PM Matthew A
(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:

x1680
x1259
x825

asked: Jan 02 '11 at 04:56 PM

Seen: 1307 times

Last Updated: Jan 02 '11 at 04:56 PM