Dynamically Add a GameObject to the Scene in Unity 3D

If you work a lot in Flash, you’re used to the process of adding a linkage name to a MovieClip in the library, and then using the new keyword and addChild method to dynamically pull the clip out of the library and display it on the stage.

You can do something very similar in Unity 3D, but the process is slightly different. Be sure to read our Flash to Unity 3D Glossary if you’re coming over to Unity 3D from Flash.

1. Create the GameObject

We’ll make it real simple. Click GameObject > Create Other > Cube in the menus to add a cube primitive to the Scene.

Create a Cube Primitive in Unity 3D

Cube Primitive in Unity 3D

A cube appears somewhere in your Scene…

Cube Primitive in the Hierarchy panel in Unity 3D

… and the Cube GameObject is listed in the Hierarchy.

2. Create an Empty Prefab

A Prefab is a lot like a Flash MovieClip. It’s going to contain our Cube GameObject. To create the Prefab, click the Create button in the Project panel, and choose Prefab from the resulting menu.

Unity 3D Project Panel Create Button

Click here …

Unity 3D Project Panel Prefab Menu

and then here …

Unity 3D Project Panel Empty Prefab

… to get this.

Right/alternate-click on the Prefab, or click and hold (Mac)/press F2 (PC) to rename the Prefab. I called mine “Cube”. This won’t create a naming conflict or anything.

3. Click/drag the Cube into the Prefab

Click and drag the Cube GameObject from the Hierarchy panel into the empty grey Prefab you just created in the Project panel. The Prefab lights up blue to indicate that it’s got junk in the trunk.

Unity 3D Project Panel Full Prefab

It’s now safe to delete the Cube GameObject from the Scene (via the Hierarchy panel) by highlighting it and pressing Delete (PC) or CMD+Delete (Mac). The Cube is safe and sound inside the Prefab.

4. Create a new Javascript

Our Cube Prefab is ready to be instantiated (instantiate == make an instance [copy] of). Let’s create a javascript to do the instantiating. In the Project panel, click Create > Javascript to make a new script.

Unity 3D Project Panel Create Button

Unity 3D Project Panel New Javascript

Unity 3D Project Panel New Javascript

Name the javascript something sensible. Then, click/drag the script onto the Main Camera. (We do this because our script won’t execute unless it’s hooked up to a GameObject in the Scene.)

5. Store a Reference to the Prefab

This is the fanciest/weirdest thing we’ll do in the entire tutorial.

Double-click the script to open it up in Unitron or Uniscite (depending on whether you have a Mac or a PC).

Declare a variable at the top of the script called myCube:

var myCube : GameObject;
 
function Update()
{
}

Save the script and close the editor.

In order to store a reference to the cube Prefab, we need to click and drag it into the variable we just created.

In the Hierarchy panel, click on the Main Camera, which is the GameObject to which we attached our script.

In the Inspector panel, look for the script component. You’ll see the myCube variable we created, and next to it is a piece of text that says None (Game Object)

Unity 3D Variable

What in the Hells?

myCube is the name of the variable (bucket), and the None (Game Object) is where the value goes.

Now, you need to click and drag the Cube Prefab from the Project panel into that value area that i’ve highlighted.

Unity 3D Click n' Drag

This is the result:

Unity 3D Variable

This is going to take some getting used to.

It’s weird. i know.

NOTE: You called the variable “myCube”, but it gets displayed in the IDE as “My Cube”. Why is that? Chalk it up to a Unity idiosyncrasy that i’m not a huge fan of. Check the script. Your variable is still called “myCube” where it counts.

6. Instantiate the Prefab

Now, with a reference to that Prefab, you’re all ready to go. Double-click to edit your script again, and punch in the following code:

var myCube : GameObject;
 
function Start()
{
     var pos : Vector3(0,0,0); // this is where the Cube will appear when it's instantiated
     var rot : Quaternion = Quaternion.identity; // Quaternion.identity essentially means "no rotation"
     Instantiate(myCube, pos, rot); // The Instantiate command takes a GameObject, a Vector3 for position and a Quaternion for rotation.
}
 
function Update()
{
}

Gettin’ Fancy

If you’ve read our article Understanding Loops with Arrays, you might have a notion of how to use Loops and Arrays to instantiate an armada of Prefabs into your scene. Here’s some sample code:

 
var myCube : GameObject;
 
function Start()
{
     // Store a bunch of different positions in an Array:
     var aPositions : Array = [new Vector3(0,0,0),
                                      new Vector3(1,2,1),
                                      new Vector3(2,1,1),
                                      new Vector3(2,0,0),
                                      new Vector3(0,3,0)];
 
     var rot : Quaternion = Quaternion.identity;
 
     // Loop as many times as there are elements in the aPositions Array:
     for(i=0; i<aPositions.length; i++)
     {
          Instantiate(myCube, aPositions[i], rot); // Put a new cube on the screen using the i'th position   
     }
}

Unity 3D Instantiation

Here’s what it looks like.

One More for the Road

Just for kicks, here’s a script that’ll throw the cubes on the screen any old place, using Random.Range():

 
var myCube : GameObject;
 
function Start()
{
     // Let's store some minimum and maximum possible x,y and z values
     // to position our cubes:
     var minX : int = -5;
     var maxX : int = 5;
     var minY : int = -5;
     var maxY : int = 5;
     var minZ : int = -5;
     var maxZ : int = 5;
     // (you can fiddle with these numbers to change the range of possible spawn positions)
 
     var totalCubes : int = 50; // Change this to whatever number of cubes you'd like to have on-screen
 
     var rot : Quaternion = Quaternion.identity;
 
     for(i=0; i<totalCubes; i++)
     {
          // Use Random.Range to grab randomized x,y and z values within our min/max ranges:
          var randomX : int = Random.Range(minX, maxX);
          var randomY : int = Random.Range(minY, maxY);
          var randomZ : int = Random.Range(minZ, maxZ);
 
          var pos : Vector3 = new Vector3(randomX, randomY, randomZ);
 
          Instantiate(myCube, pos, rot); // Put a new cube on the screen using a randomized position   
     }
}

Unity 3D Random Instantiation

Awesomazing.

24 thoughts on “Dynamically Add a GameObject to the Scene in Unity 3D

  1. Unity McJimmy

    First… I loves me the Unity.

    Second… I’ve always found this process bizarre.
    Prefabs are both classes and objects… blows me mind.

    I’ve tried to instantiate prefabs directly (without the drag & drop reference).
    The closest I got was instantiating a prefab from the resources folder:
    GameObject newCube = (GameObject) Instantiate(Resources.Load(“myCube”));
    This only works if you dump your prefabs in the Resources folder,
    something Unity actively discourages. Apparently that folder is evil.

    Reply
    1. Ryan Henson Creighton

      Yeah – it always seemed weird to me that Resources.Load would only pull from the Resources folder … by that right, shouldn’t you be able to create a folder called Enemies, put all your enemy Prefabs in there, and call Enemies.Load ? Apparently not.

      This whole drag and drop thing is not the most elegant solution, and i know it drives “egghead” programmers insane.

      Reply
  2. Rob Klimm

    You’ve unfortunately confirmed my worst fears. There’s absolutely no way to pull a prefab from the library without an editor reference variable to the prefab. So in an actual game I’ll need an entire object and script only dedicated to holding references to all the conceivable objects I might use at any time. A least if there was SOME way to pull them from only code :/

    Reply
    1. Ryan Henson Creighton

      Lots of ways to skin a cat, Shea. This is another one, but as the guide mentions, there are advantages and drawbacks to each method. i actually find both of them kind of lacking.

      Reply
  3. Angelo

    I actually didn’t even noticed how annoying the prefab instantiation thing is until I read this. Even making a prefab should be easier, why can’t I select an existing hierarchy and convert it to a prefab?

    Also, I know it’s not the point of the tutorial, but if anyone ever just wants to instantiate a primitive like a cube you can do if from code:
    var cube : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);

    And an empty GameObject with this:
    var empty = new GameObject(“new name for the object”);

    Reply
    1. Ryan Henson Creighton

      Thanks for the tip, Angelo. Your “convert to Prefab” suggestion makes a lot of sense. Have you told the Unity guys about it?

      Reply
      1. Angelo

        A great thing about unity is the customizable editor. And after writing my comment I needed a ‘Convert to Prefab’ button in my life, so I wrote one that also adds it as an option to the GameObject menu and the shortcut cmd+i.

        They had the perfect editor functions just sitting there, so I’m not sure why it’s not already standard, but you can get it in your unity with this script download: http://bit.ly/g2L8NQ
        (unity nuubs: move it to “Assets/Editor/” to make it work.)

        Reply
  4. Unity McJimmy

    Found a reason why Unity wants a member variable “drag ‘n drop” reference:
    http://unity3d.com/support/documentation/ScriptReference/Resources.html
    “When using this technique Unity can automatically calculate which assets are used when building a player. This radically minimizes the size of your players to the assets that you actually use in the built game.”

    I question the wisdom of keeping unused prefabs in your Unity project,
    especially given the code approach required to support it.
    Then again I’ve never worked on a large Unity project,
    alongside the disorganized and sloppy.

    Also… I suspect Unity might use these references when deciding the order of streaming Prefabs.

    Thoughts Internet?

    Reply
    1. Angelo

      It seems to me that they would be able to offer some kind of code equivalent to drag and drop, that is still strict enough for asset stripping. Like a preprocessor directive, so they don’t have to worry about prefabs being referenced dynamically.

      I could live with:
      #prefab MyCube “my cube”
      That creates a variable MyCube linked to the prefab “my cube.prefab”

      But I’d rather be able to instantiate prefabs dynamically, even if its only from a special folder. They already have a special Editor folder and there’s the Standard Assets folder, why not have a special rule for the Prefabs folder?

      Reply
  5. mipago

    Hi Ryan and I got your book and finished it but I need more information as well as the book.
    thanks for this article please post all this with screenshots as well as hopefully also enclose the project would help us much for which we are beginning a hug and thank you very much

    Reply
  6. Unity Programmer

    When you Instantiate the cubes how do you the reference them later?

    e.g If I wanted to move the 3rd cube created what would I use?

    thanks!

    Reply
    1. Ryan Henson Creighton

      The Instantiate command returns a reference to the thing that you instantiated. So you just capture that reference in a variable:

      var box3:GameObject = Instantiate(myCube, pos, rot);
      Reply
  7. Ricardo

    Hi i want to add a box collider to my prefab but it didnt work.

    what i want to do is two cars, and when they collide i do something.

    Thanks.

    Reply
  8. Hizral84

    Hello there, have a problem here, I manage to instantiate my GameObject. But they will sometimes overlap each other. How do I prevent the GameObject from overlapping each other.

    Some people told me to used Array to store the position, so the GameObject can check if another GameObject about to instantiate at the same place it will instantiate again to another place.

    How do I do this? kindda lost here.

    Reply
    1. Ryan Henson Creighton Post author

      Sure! Whenever you instantiate something, store a reference to it in an array. Keep another array full of spawn points (probably Vector3’s … positions in space). Whenever you want to instantiate something new, build a nested loop. In the outside loop, loop through all of your spawned points. In the inside loop, loop through all of your spawned objects, and compare their current positions to the spawn points. Build a temporary list of all the spawn points that don’t already have a thing in that position. You’ll end up with a list of available spawn points. Randomly grab one of those available spawn points, and spawn your new thing in that position.

      Reply
      1. Hizral84

        Okay thanks for the info, But what if I just instantiate the game object randomly on the screen without constrain. How do I store the position? or is there another way to do this without using array.

        Reply
        1. Ryan Henson Creighton Post author

          i’m a bit rusty because i’m not developing in Unity right now, but to store the position, create a variable, and then say myVar:Vector3 = myInstantiatedGameObject.transform.position. Something like that?

          Reply
  9. Pingback: Some of the best references for beginners in Unity3D. | Iamsidv - Just another Game Developer's Blog

  10. Pingback: Some of the best references for beginners in Unity3D | Creatiosoft Solutions Private Limited

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.