Instantiating a Prefab from a Project

Hi, is there any way to instantiate a prefab that exists within the project, but does not exist in the scene. I tried to use GameObject.Find():

Object=GameObject.Find(“Cube”);
instantiate(Object, transform.position, transform.rotation);

…but this only returns a gameobject if it exists within the scene (so for my purposes, it’s NULL).

Is there an alternative command that can instantiate a prefab from the project). Much appreciated for any help.

Thanks

you can make a variable which holds your prefab like so:

var myPrefab : Transform;

if(some condition){

var bullet = Instantiate(myPrefab, gameObject.Find("spawnPoint").transform.position, Quaternion.identity);

}

In this code I use an empty gameobject called spawnPoint to set the initial position of my prefab. Use whatever you see fit :slight_smile:

p.s: Forgot to mention that you need to drag your prefab from hierarchy view onto the “myprefab” variable in the inspector of this script.

Assuming cube has your prefab.U need a script with a variable of type cube.u can initialize the variable via inspector.

Example:
var cube : Rigidbody;

initialize cube in inspector view by drag the prefab from the project.

then in script

var L_variable = instantiate(cube, transform.position, transform.rotation);

Thanks for the response - this all makes sense to me, but this reliess (as you say) on dragging the prefab from the hierarchy - if I want to instantiate one of several prefabs, this solution wont work will it (as I can only drag one prefab onto the variable).

Obviously I meant to say “drag from project view onto variable in inspector”, but I’m sure you got the point :wink:

Anyways, im not sure I understand what you want then? Do you want to instantiate a nonspecific prefab, or just one of many? if its one of many, then I cant come up with any other solution than to repeat this process loads of times (as in making loads of variables and dragging loads of prefabs onto them)

Ok to give you a bit more background (I’m new to this - so it’s probably me that’s missing the point here :slight_smile: ). I have created a list of prefabs, each of which are differnet shapes (not really relevent, but a bit of background).

I have a script which generates a random number and based on that number, I want to instantiate one of these prefabs to appear in the scene (which dont exist in the scene before I instantiate them).

Thats what I’m trying to do…

:lol:

Use Theformand’s route for stroring your prefab but put it into a function, ie;

function CreateCube();

now create a duplicate of that function but as

function CreateSphere();

In those you can set your different prefabs per function (using the inspector as Theformand stated).
Now when you want to instantiate a particular prefab you just call the function for the required one.

var prefabs : GameObject[];

function Start () {
   Instantiate(prefabs[Random.Range(0, prefabs.Length)]);
}

–Eric

Ok I think I’m missing a key concept from my side here. My understanding is Instantiate creates a copy of the object - so how can copying a transform (which as I understand is just a location of an object, or is it an actualy empty GameObject?) If it is, why not declare it as var myPrefab : GameObject;

If its not, how can it store my prefab? Thanks for your patience!!

transform.position sets the position of the transform(object)

Yes the Transform stores all the location,rotation etc data on the object, but as every object in the scene has a transform it can be easier to reference the transform of the object rather than the object itself, since you often want to change values in the transform anyway.

At least thats my understanding of it and I manage to fudge along happily :wink:

ok cheers, although I must admist I find it confusing :frowning:

bishylewis, I am right with you! Everywhere I look there are no explanations about just instantiating a prefab straight from the inspector. It seems like Unity (and all the support guys) are forcing us to drag and drop, drag and drop. I’m new to this stuff so I don’t know why exactly… With the stuff I’m doing I am HATING this drag and drop all over the place and wish I could just instantiate a prefab easily. Like you I am sure something just isn’t clicking with me…
There is the EditorUtility.InstantiatePrefab command but I have no idea how it works…it seems like it is ALSO a drag and drop thing of some sort.

Am I getting this all wrong and is there an easier way to instantiate a prefab WITHOUT dragging and dropping the prefab into some object/script in the scene somewhere? And if not is there a reason why not (just curious if it has something to do with optimization or whatnot).

Thanks, and sorry for the rant… I find SOOOO much about Unity pure awesomeness! This is a great program… just some things are hard to understand sometimes.

I don’t understand the hate. Dragging and dropping takes a second or two, and is the easiest way you could handle this. It only becomes a pain if you have many many objects that you need to add at once, such as for a huge array.

In that case you can use Resources.Load, but keep in mind the disadvantages: everything in Resources is included in your build whether you use it or not, so you lose the ability to automatically exclude stuff you’re not using. Plus you’re hard-coding the information into your script, so if you rename or move things, you have to keep track of this manually instead of just letting Unity handle it.

–Eric

+1

We, the UT crew, are happy to explain and have done so many times how to instantiate things either by establishing a reference via inspector drag-and-drop variable assignment, or by loading things from a Resources folder. Any inclination to get you to use the Inspector route in particular is because it’s generally for your benefit as it’s usually far easier and offers a more optimized experience. If you want to instead use a Resources folder (losing build size optimizations by the editor, do name-based lookups/finds instead of pre-done drag-and-drop assignment, etc.) then go for it, just be sure the reasons for that are proper (examples: data driven applications where you may not know what you’ll need to load until run-time when you pull in that data). We’re happy to explain either way, I don’t get the hate towards drag-and-drop nor the beef you seem to be having with our staff and what we recommend/suggest/instruct.

Oh, and Beskull, if you want to load/instantiate prefabs without dragging/dropping then as we’ve noted you need to use a Resources folder, read this:

Resources

Higgy and Eric,
Hey I don’t want you guys to take my post the wrong way. Like I said at the end there is a lot of pure awesomeness in Unity and makes things SO easy. I do like the drag and drop aspect of most things quite a lot. It is just a little odd (not understanding the structure or behind the scenes setup of things) to not be able to access a prefab the same way you can an object.

I do think that I’m starting to understand how exactly things work now though from all of the countless posts that you guys put up. (once again greatly appreciated) I think that some of us newer users see all of the files in the inspector view and just think we can naturally use anything - when the idea is that you need to somehow link it or add it to the scene in some way.

In a way, one could just make a long script and drag all of the prefabs into the script and you’d have access to them all from there (an seemingly extra step yes, but now the information is linked to the scene in a way).

I’ll have to try out the resources class but in general I am not confident in my abilities quite yet to use it.

Thanks for the timely reply guys, and the hate was mainly vented frustration from two days working on the prefab linking idea and trying to get it straight. So many times it comes down to just thinking about things in an entirely new way… and this is another one of those.

Btw I just jumped into sound, and props to you guys on how you set it up. I think the listener idea is awesome and it is SO easy to throw in 3D sound now. Good job on sound.

-Beskull

p.s. Any chance a lightning particle option will be added in future builds? (line renderer with branching paths?)

I think much of the frustration comes from the lack of documentation (or “obvious” documentation location") for accessing the cogs behind the curtain of the Unity Editor. Yes it’s been explained how you can reference things, but it’s usually discouraged due to the ease of drag-and-drop, but also the fact that it DOES push limitations on you that don’t exist for d+d. For example, as you point out, any manual loading has to be done from a Resources folder, and not just anywhere.

One thing that might confuse is that you use a Transform variable in your script to reference a prefab. I am not totally updated with the underlying class hierarchies but I support that Transform somehow is a base class of all objects. So that is why you can use a Transform to hold a more complex object.

The drag&drop thing should work for most cases. Where I don’t really find a good solution is in the following scenario:

  • A game loads and I chose to run vehicle A with weapons 1 and 2. The other players chose vehicle B, B, D and B with other weapon configurations. How do I start up the game by instanciating things based on GUI choices? Do I have to have a script that has Transform references to all vehicles and all weapons and pick the right ones?

/Ricky

I am currently struggling in what way i will create a SpawnTrigger class and EnemyFactory class.

First idea is that the the spawntriggers on the maps will hold a reference to a “basic enemy” prefab and instantiate new enemies from that one. (this means 7 spawnpoitns will hold 7 references to the prefab).

Second idea is to create a factoryprefab that all spawntriggers has a reference to, and spawntriggers calls the factory method “Spawn” that will resource.load in prefabs as they are used and save a reference in itself, so if a second spawntrigger wants to spawn a “basic enemy” the resource is loaded and kept in the factory and is just returned

Third idea is that i drag and drop the enemies that are to spawn at this specific scene, and every gameobject can call Gameobject.findbyname(“Factory”).getcomponent.spawn(“whatever mob”).

These prefabs would ofcourse be loaded when the level is loaded and not on the fly when they are called.
I dont have trouble in doing any of these solutions but i fail to find information or test what is best out of an optimization point. If anyone could shed some light on this i would be very grateful.

Jerry Jonsson
Producer and Programmer - http://trashtalkgames.com/

Just to reference this a bit for my specific use case. I have two use cases I think using the resources folder is what I want to do, and want to run this by you guys to make sure I have this right.

Use Case 1: Character Choices for Players
4 Players - n Character Choices (depending on content they’ve downloaded or if they are using our cloud services).
The players choose their characters, and then click start, I save the name of the prefab they chose and when the level is loading, do Resources.Load(“CharacterName”) and then add components specific to their other choices. Do those components also have to live in the Resources folder (“ie, the BigBadSword script”)

Use Case 2: GUI Skins for various characters and or Seasons.
Depending on a few calculations we reskin the whole GUI and add extra Audio. Example (3 players picked Christmas characters, 1 player picked a Halloween character). We re-theme with Christmas and add audio that slams the Halloween Character. Do we load those assets from the resources folder?

Reason…I really don’t want to keep every character and every GUI skin in memory. I would prefer to leverage that extra memory for more creative uses. We plan to just keep adding characters and skins until we come up with a better hobby.