Category Archives: Blog

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

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

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.

How to Start a Game Project in Unity 3D

By default, a new Unity install opens with a demo project. Unity 2.6 had an island, while Unity 3.0 has a G.I. Joe-style first-person shooter game. Follow these steps to start your own game project from scratch in Unity;

1. Start a New Project

New project in Unity

Click File > New Project …

Project Wizard in Unity

Every Unity sits in its own folder. In this dialogue, browse to or create a new folder where your project will live, and then click the Create button.

What you’re left with is this:

Blank Project in Unity

Ok – where’s the “Make Game” button at?

Here’s what’s going on behind the scenes:

Unity Project Folder

Unity automatically creates three sub-folders in your Project folder. You won’t have to touch these folders – in fact, you really shouldn’t, because there’s metadata in there that might get botched if you start poking around. Most of the time, you can import assets directly through the Unity IDE (program).

2. Make a Scene

Unity Projects are comprised of Scenes. In Flash, it wasn’t really a good idea to use the Scenes, but in Unity, it’s darn near a requirement. What you’re looking at now is actually an unnamed Scenes. Scenes must be saved individually … whenever you try to leave one Scene to look at another, you’ll get a Save Confirmation prompt.

The smartest thing to do right off the bat is to save this Scene.

Unity Save Scene As

Go to File > Save Scene as …

Unity Scene Name

Choose a name for your Scene. Some really simple examples are “Title”, “Credits”, “Win”, “Lose”, and “Game” for an extremely basic project. i’m calling this one “Game”, which is where all my main game action will take place.

Once you hit “Save”, two wonderful things will happen:

Unity Title Bar

The name of your new Scene is reflected in the Title Bar of your project …

Unity Project Panel

.. and a new Scene shows up in your Project panel.

The Project panel is where all your stuff goes. It’s very much like the Library in Flash. Scenes have a little Unity 3D icon next to them.

Put Your Scene in a Folder

The final thing you’ll want to do is to create a folder for your Scenes, and dump your Scene inside it.

At the top of the Project panel, click the Create button and choose “Folder”:

Unity Project Panel Create Button

This button sees a lot of use in Unity.

Unity Project Panel Create Folder

While you’re here, check out all the other cook junk you can build.

You can also right click or alternate click on the Project panel to bring up this menu. Mac users can probably splat-click or some nonsense.

And then:

Unity Project Panel Scenes Folder

Rename the folder “Scenes” by right/alternate-clicking, slow double-clicking (Mac) or pressing F2 (PC)

Unity Project Panel Game Scene in Folder

Drag and drop the Game Scene inside the folder. Click the grey arrow to see what’s inside the folder.

What Now?

How do i learn Unity 3D?

To learn more about developing games for Unity 3d and to learn the basic controls for getting around the program, read the first chapter of my book Unity 3D Game Development by Example. Next, buy four copies of the book (in case you accidentally drop three of them in the mud).

How do i build a timer in Unity?

When you’re a little further along, read this sample of Chapter 7 of my book, Don’t be a Clock Blocker. That’s how.

How do i program in Unity?

If you need a little help with programming in Unity using javascript, read our Understanding Programming in Unity Javascript series.

How do i transition from Flash to Unity?

Check out our article on Five Common AS3 to UnityScript Translations.

Alright – what else you got?

Like our style? For more free Unity 3D tutorials, sign up for our Unity 3D Game Development by Example newsletter, and we’ll send out a link whenever we post a new tutorial or article on Unity 3D.

Go forth and game!