Asteriods – Instantiating Objects
Now that we have made a prefab for our asteroids we need a way of adding them to our scene. We can do this by using instanciate.
First things first we need to add a script to handle our asteroids. Let’s create a new empty object called Asteroid Manager.
Add a new script to the object called AsteroidManager.
We need a way to refer to our asteroid prefab so we need to declare a public GameObject called asteroid. This way we can set our asteroid prefab in the inspector.
We currently have 3 Asteroids in the scene already. If you have already deleted them add them back in and put them in roughly the same positions they were in previously. Make a note of these positions by looking at the objects transform in the inspector. My asteroids are at (6.35,0,4.22), (5.02,0,-7.12) and (-8.76,0,2.7). We will use these positions in a moment.
Once you have the positions noted down delete the asteroids in the scene.
Next declare a public int called numberOfAsteroids in the AsteroidManager script. We will use this later on to easily control how many asteroids are instantiated. For now set this to 3 in the inspector.
Make a new method called InstantiateAsteroid. It should be void method. For now we will hard code to instantiate 3 asteroids as we have not covered for loops yet (we will cover these after we cover ridged bodies in the next part). To begin with we will just do one. To do this we use the instantiate function on our prefab object: Instantiate(asteroid)
Call the InstantiateAsteroid method in the Start method and press play. An asteroid should appear in the hierarchy and in the scene (where the prefab transform is set to).
Great we have just instantiated our first game object. Now we can copy and paste the code a couple more times and instantiate 3 objects.
Now how do we get the objects to appear at the points we had before? Well looking at the documentation the instantiate function can be passed a position and rotation. The object will then appear at that position at that rotation. So lets pass our 3 instantiations our positions we took note of earlier. We will also pass a rotation of zero. Dont worry to much about understanding what is going on in the code shown below at the moment. A Vector3 is essentially a vector with X, Y and Z positions and a Quaternion is a rotational vector. The new is there to create the vectors. The numbers in the Vector3 require an f after them to tell the vector they are floats and not doubles.
Now save and hit play
One last thing we can do to tidy up a little bit. We should make the asteroids children of the Asteroid Manager Object. To do this we simply pass this.transform to the instantiation as well. Parents are represented as transforms and this script is a component of the Asteroid Manager object; so by saying this.transform we are finding the transform associated with this script which is the transform we need.
That concludes this part. In the next part we will look at RidgedBodies