Search Unity

Instantiate Asset from Project -- Inside Code (Completley)?

Discussion in 'Scripting' started by nchatterjee, Nov 22, 2007.

  1. nchatterjee

    nchatterjee

    Joined:
    Nov 22, 2007
    Posts:
    3
    I'm new to Unity, but I am evaluating it for a very specific use at my company.

    In my playing around I've run into a little problem that I can't quite figure out. Hopefully the good people on the forums can help me out.

    I want a script to instantiate a prefab. The prefab exists inside of my project but not inside the Hierarchy.

    I *can* achieve this by doing pretty much what's in the tutorials and making the script like this:

    Code (csharp):
    1. var obj : Transform;
    2. function OnMouseDown () {
    3. Instantiate(obj, Vector3(0,0,0), Quaternion.identity);
    4. }
    ... then attaching the script to an object in the scene and setting through the editor the value of obj to the asset that I want to instantiate.

    However...

    I need to do something different! I need to be able to instantiate an asset completely programatically from inside the script, without using any external variables or setting anything through a drop-down menu. Here's an example of what I want to do:

    Code (csharp):
    1.  
    2. var arrayOfAssetName = ("this", "that");
    3. function OnMouseDown() {
    4. for (var assetName in arrayOfAssetName) {
    5. var obj = functionIHaventFoundYet(assetName);
    6. Instantiate(obj, Vector3(0,0,0), Quaternion.identity);
    7. }
    8. }
    9.  
    So...

    is this possible? Is there any way to do a thing like this?

    Can someone help me fill in my functionIHaventFoundYet? Or is there another way to do it?

    Many Thanks!
    N
     
  2. Jonathan Czeck

    Jonathan Czeck

    Joined:
    Mar 17, 2005
    Posts:
    1,713
  3. shaun

    shaun

    Joined:
    Mar 23, 2007
    Posts:
    728
    I used to use the Resources feature, but it can be risky and needs a custom build script.
    Having said that, I haven't found a perfect way to organize and load a large number of assets at runtime.

    Jonathan - what kind of technique are you using for your large projects?

    Cheers
    Shaun
     
  4. nchatterjee

    nchatterjee

    Joined:
    Nov 22, 2007
    Posts:
    3
    Thanks guys! That did the trick! (well, gets me halfway)

    Is there a way to load a resource (like "Import Package...") from a file dynamically?

    Cheers,
    N