Tag Archives: Unity3D

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.

Turn Something Invisible in Unity 3D

thing.renderer.enabled = true; // or false

… where “thing” is a reference to a GameObject.

If you’re doing this in a script that’s attached to the GameObject you want to hide, try:

gameObject.renderer.enabled = false;

Note that the GameObject’s collider is still active, so the GameObject can still be clicked on, run into, etc. Here’s a fast way to make the GameObject’s collider inactive:

gameObject.collider.isTrigger = true;

To disable the GameObject’s clickability, do this:

gameObject.active = false;

Flash to Unity 3D Glossary

If you’re thinking of transitioning from Flash to Unity 3D, you’re in luck: the two programs are very similar, and it shouldn’t take you very long to feel right at home. The biggest difference that i can see between the two is that Unity is a proper game engine, while Flash is a program that you bully, beg and cajole into doing game-like things. Want collisions, 3D depth-swapping, particle systems, physics, shaders, and a whole lot more right out of the box (instead of implementing Box 2D, Away 3D, Collision Detection Kit, and God knows what else)? Unity is a real treat!

Here are a few glossary terms that kinda sorta carry over from Flash to Unity:

MovieClip == GameObject (but more accurately, Symbol == Prefab. Much like a MovieClip/Graphic/Button in Flash, whatever changes you make to a Prefab in Unity will replicate to all instances of that Prefab)

Scene == Scene (but Scenes in Flash are generally useless and glitchy … Scenes in Unity are the bee’s knees)

Unity 3D Scenes

Unity.

Library == Project panel

Flash Library

Flash.

Unity 3D Project Panel

Unity.

Properties panel == Inspector panel

Properties panel in Flash

Flash.

Inspector panel in Unity

Unity.

Timeline == A-NOTHING!! (except that there IS a timeline that allows you to animate GameObjects. The resulting animation is stored in an .anim file inside your Project panel. You can apply an animation to any GameObject in your Scene, so animations are curiously reusable)

Timeline in Flash

Flash.

Timeline in Unity 3D

Unity. (warning: the UX [user experience] on this thing kind of blows ass.)

Instance names == tags … sorta (but unlike in Flash, you can have multiple GameObject instances with the same tag)

Flash.

Unity.

Layers == layers (but Unity does not display its layers in anything nearly as nice as the Flash timeline)

Flash.

Unity.