Unity Scripting: Instantiation

  • Unity Scripting: Instantiation

    Unity Scripting: Instantiation

    Posted by FIZIX Richard on Wed 4th July 2012 1:14am

    In this tutorial we will be looking at an important concept of games development; instantiation. The process of instantiation or instancing as it is also known, is where you load or create objects at runtime through scripts.

    Normally, when you want an object to appear in a scene or level you place it from the library into the scene and position it in 3d space. This is useful for static objects or objects that always appear in a specific spot. However in your average game, there are many things that do not appear in a specific spot, all the time.

    If we think about what objects appear in a game that are instanced (i.e. created dynamically through code or "spawned") here are just a few examples:

    - Monsters / Creatures / Enemies
    - NPC characters are often instanced
    - Player characters are also often instanced
    - Quest items in RPG's
    - Rewards - such as rings in Sonic games or chests in RPG's
    - Components of puzzle games

    So in summary, instantiation is simply the process of dynamically spawning an object as opposed to it being manually placed in a scene. As you can probably imagine, this topic can get very long and incredibly complicated when you consider different types of game mechanic and how the implementations of instantiation could be formed.

    Therefore we will start with some very basic technical examples and then move onto more practical implementations.

    The Instantiate Function (the basic, basics)

    Fortunately Unity has a function built in called "Instantiate()", which makes instantiation easy to get to grips with, where things get complex is getting the finer details or specific implementations of a mechanic off the ground. For example, creating spawn areas where monsters appear and respawn on timers randomly within the defined region of a scene against specific rules such... think of how monsters appear and reappear after death in an MMORPG; it's when your implementation starts to take a practcal approach like that, when things get truely complicated.

    Needless to say, we won't be doing that in this tutorial, but we will be going over the foundations of instantiation so that you can at least have an idea in your head about how you create such mechanics and maybe even be able to implement such mechanics with a little research. We might create a tutorial on that kind of implementation but its early days for Unity Labs yet.

    Anyway, back on topic; the Instantiate function itself; in its most basic form, the Instantiate function takes three parameters and looks like this:


    Instantiate(object, position, rotation);

    object is the prefab you want to spawn (i.e. a treasure chest)
    position is the position in 3d space you want it to appear (i.e. x: 300, y: 1, z: 250)
    rotation is the direction you want it to be facing

    A note on the object to pass; this is done through the use of a variable which will hold the object (a public member variable). If you have done a few other tutorials, such as your Game Start Screen tutorial, you will have encountered a scenario where we created a variable at the top of the script which we used to reference a GUISkin. We reference the object to spawn in much the same way, by declaring a variable as a GameObject or a RigidBody (depending on the object we want to spawn) and assigning an object to that variable.


    var treasureChest : GameObject; Instantiate(treasureChest, position, rotation);

    Instantiating a normal game object in code would look something like the example above. We define a variable (i.e. treasureChest) as a GameObject which is passed to the Instantiate function. For it to work we would have to assign an object to the variable first, but thats roughtly how it works.


    var rigidBodyObject : Rigidbody; Instantiate(rigidBodyObject, position, rotation);

    The example above would set the variable to a Rigid Body type, so only Rigid Body objects could be passed to the function.

    With passing the object to the function explained, lets quickly explain the position and rotation, we tell Unity where to position the object and its rotation using a Vector3(x, y, z) function, which is a mathematical functon for defining coordinates in 3D space.


    var treasureChest : GameObject; Instantiate(treasureChest, Vector3(0, 5, 10), Vector3(0, 0, 10));

    In the example above we spawned a treasure chest object at position X: 0, Y: 5, Z: 10 with a rotation of X: 0, Y: 0, Z: 10.

    You also have to consider local space and world space:

    - World Space is where you reference co-ordinates based on the entire scene (i.e. x,y,z position from the 0,0,0 point in the scene)

    - Local Space is where you reference co-ordinates based on another object such as the player character (i.e. x, y, z position from the character)

    I hope that all makes sense, if not the technical implementation below should help.

    Moving on we will be spawning objects in a simple scene, this technical example should show you various ways in which you can instance objects in your game world.

    So to start off, lets create a new project called "Instantiation Tutorial 1", include the standard assets package. Then go to "GameObject -> CreateEmpty" to create an empty game object which you can see in the Hierarchy. Then rename that object to StartUp.

    Now in the Project Library select "Create -> JavaScript" and call the new script "Instances". Then select the StartUp game object in the Hierarchy and go to "Component -> Scripts" and select the Instances script to assign the script to the StartUp object, causing the script to execute when we play the game automatically.

    Now create a terrain, paint a grass texture and place the FPS controller from the Prefabs folder in the standard assets package into the scene so you can walk around.

    Now we will start to instantiate objects in this scene.

    A Basic Implementation

    Lets create a real basic implementation to start, we're going to create a primitive object (a cube) and drop it in the scene using code:


    function Start () { var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); }

    This simple block of code in the start function will create a cube which you should see plop down on your terrain.

    Lets make this one a bit more interesting:


    function Start () { var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.AddComponent(Rigidbody); cube.transform.position = Vector3 (42, 4, 37); var cubeb = GameObject.CreatePrimitive(PrimitiveType.Cube); cubeb.AddComponent(Rigidbody); cubeb.transform.position = Vector3 (42, 4, 37); var cubec = GameObject.CreatePrimitive(PrimitiveType.Cube); cubec.AddComponent(Rigidbody); cubec.transform.position = Vector3 (42, 4, 37); }

    What we have done above is create 3 different instances of the cube, except this time we have given them a Rigid Body component and controlled their position so they drop on top of one another.

    You might want to position your camera or player controller so that you can see 42, 4, 37 on startup, you will see the cubes fall onto each other and bounce. They are bouncing as they have a rigid body component, which makes them react to each other (collisions at work there).

    So there are the basics of instantiation; we will create a few applied tutorials soon, which will put all of this stuff into real practice and bring it all into context; but this is enough to get started.