7. Instantiate

uke 的头像

It is often desirable to create objects during run-time (as the game is being played). To do
this, we use the Instantiate function.
Let’s show how this works by instantiating (creating) a new game object every time the
user presses the fire button (either the left mouse button or left ctrl on the keyboard by
default).
So what do we want to do? We want the user to move around as usual, and when they hit
the fire button, instantiate a new object. A few things to think about:
1. Which object do we instantiate?
2. Where do we instantiate it?
Regarding which object to instantiate, the best way of solving this is to expose a variable.
This means we can state which object to instantiate by using drag and drop to assign a
game object to this variable.
As for where to instantiate it, for now we’ll just create the new game object wherever the
user (Main Camera) is currently located whenever the fire button is pressed.
The Instantiate function takes three parameters; (1) the object we want to create, (2) the
3D position of the object and (3) the rotation of the object.
The complete code to do this is as follows (Create.js):
var newObject : Transform;
function Update () {
if (Input.GetButtonDown("Fire1")) {
Instantiate(newObject, transform.position, transform.rotation);
}
}
Don’t forget that transform.position and transform.rotation are the position and rotation of
the transform that the script is attached to, in our case this will be the Main Camera.
However, when an object is instantiated, it is usual for that object to be a prefab. We’ll
now turn the Cube1 game object into a prefab.
- Firstly, let’s create an empty prefab. Select Assets->Create->Prefab. Rename this
prefab to Cube.
- Drag the Cube1 game object from the Hierarchy View onto the Cube prefab in the
Project view. Notice the prefab icon changes.
Now we can create our Javascript code.
- Create a new Javascript and name it Create. Insert the above code.
- Attach this script to the Main Camera and assign the Cube prefab to the newObject
variable of Main Camera.
- Play the game and move around as usual. Each time the fire button is clicked (LMB or
left ctrl) and you should notice a new cube appearing.