x


Struggling with Instatiating a prefab

I'm trying to Instatiate a Prefab by looking it up. The following code works:

var explosion: GameObject; 

function update()
{
  ....somestuff...
 var newexplosion = Instantiate (explosion, hit.point, transform.rotation);
}

This relies on me assigning the Prefab in the Editor's Inspector. But what I really want to do is:

function update()
 .... somestuff....
var newexplosion =Instantiate (GameObject.Find("Explode"),hit.point,transform.rotation);
}

This doesnt work unless I have an instance of the prefab Explode called "Explode".

Hence, what I want is to instatiate an object using the prefab's name.

Its no doubt a very newb question but I just cant seem to get it.

more ▼

asked Oct 31 '11 at 11:05 PM

Fabkins gravatar image

Fabkins
675 15 20 26

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

2 answers: sort voted first

You need to load the resource and then instantiate that reference:

  var myprefab : GameObject = Instantiate(Resources.Load("myprefab"));

Note this will only load assets stored in the resources folder .. also I've noticed that the resource database might not have a link to your prefab (if you just created it) so I suggest adding this line initially:

  //Remove before build/release
  UnityEditor.AssetDatabase.Refresh();
more ▼

answered Oct 31 '11 at 11:25 PM

Rod Green gravatar image

Rod Green
2.9k 2 9 42

Perfect, thank you guys. Here is what the line looked like:

var newexplosion : GameObject = Instantiate(Resources.Load("Explode",GameObject), hit.point, transform.rotation);

After I copied the Prefab into a folder called "Resources" as instructed.

Is this quite a heavy routine? Does the resource get cached? Should you preload any resources you think you may want to use?

Oct 31 '11 at 11:52 PM Fabkins

I think unity might cache it internally however I would cache it to be safe.. i.e.

  if(myprefab == null)
        myprefab = Resources.Load("myprefab");

  var myInstance : GameObject = Instantiate(myprefab);
Oct 31 '11 at 11:58 PM Rod Green

Looks like you can also load many using Resources.LoadAll and address them via an array.

Again thanks.

Nov 01 '11 at 12:08 AM Fabkins
(comments are locked)
10|3000 characters needed characters left

If you put the prefab in a "/Resources" folder, you can use Resources.Load.

more ▼

answered Oct 31 '11 at 11:24 PM

kevork gravatar image

kevork
415 1 2 4

(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:

x1249
x13

asked: Oct 31 '11 at 11:05 PM

Seen: 606 times

Last Updated: Nov 01 '11 at 12:08 AM