Instantiation of a prefab (solved)

Can I instantiate a prefab only by script?

I have a prefab in my project list (so not “active”, not in the hierarchy) and I want to instantiate it by script. So not by adding it to a variable in the inspector, but find the prefab by its name or tag or layer and instantiate it.

Is it possible? :slight_smile:

Thanks a lot

Why not? Just drag’n’drop.

–Eric

Because it’s an independant script I call in another script. It is not linked to any gameobject :slight_smile:

Sorry I was maybe not clear ^^

Still not clear I’m afraid…all prefabs are gameobjects. All you have to do is drag the prefab onto the slot in the script. Whether it’s in the hierarchy or not is irrelevant…in fact, I’m not sure under what circumstances you’d want to instantiate an object from the hierarchy.

–Eric

I don’t know how to explain exactly.

There is no slot because the script is not a component of an object. it’s just a js file alone, this js file is called by another script and in this independant js file, I need to access a prefab.

Example:

this js file is linked to my character

var indeJS : IndependantJS;
if(Input.GetButtonDown("Fire1"))
{
indeJS.dosomething();
}

and this is the independant js file:

var target : gameobject;

static function dosomething(){

Instantiate(target, someVector3Data, someRotationData); 

}

So if the script was a component of a gameobject I can drag and drop the gameobject, but not if the script is independant

Is it more clear? :slight_smile:

Now maybe it’s not a good idea to do like that, but I just wanted to know if it was possible

I can do it another way :slight_smile:

You can do that if your prefab is located in a folder called Resources

See:

Note that any assets in folders with that name will always be included in the game no matter if they are used or not, so use with care!

Rune

Ho, many thanks :slight_smile:

Not exactly the behaviour I expect for now, so I will use another way, but it can be usefull for other projects :wink:

Thanks a lot ;)[/code]

Well, to clarify, the asset will be part of the game data and thus make the file size of the game bigger. I did not mean that the asset will be visible in your scenes if you don’t instantiate it.

Rune

Awesome :). Just as I was struggling with this same issue, the pertinent question is asked and then answered. Thanks :).

Yup, I understood that :wink:

Thanks again :wink: