Unity 3D Scripting Examples and Exercises: Worksheet Ten

You will need to refer back to previous examples and exercises and transfer the concepts and techniques introduced when carrying out this worksheet.

Refer to the associated lecture notes Instantiating World Objects for the overview of instantiating objects in Unity.

  1. Create a new Plane object, name it Ground and position it in the World at (0,0,0)
  1. Create a sphere object, Name it Ball and attach a green material.
  1. Select the Ball in the Hiearchy and from the Inspector Window choose

Add Component, Physics, Rigidbody, Add Component, Physics, Constant Force.

In the Inspector Window set the Rigidbody properties with a Mass of 10, and set the Constant Force - Force Z value to -20

  1. Create a Prefab from the Ball sphere you created in steps 2 and 3.
  1. Delete the existing Ball sphere from the scene.
  1. Create a new Cube object and name it InstantiateCube.
  1. Position the Cube in the World at the centre of the Ground’s X-axis and just above Ground’s surface.
  1. Create a new script called Instantiate and add the following line of code before the Start() function:

var ballInstance : GameObject;

  1. Add the following code inside the Start() function.

Instantiate(ballInstance, transform.position, transform.rotation);

  1. Attach the script to the InstantiateCube.
  1. Drag the Ball Prefab from the Assets Window and drop it onto the ballInstance variable slot in the Inspector Window.
  1. Run the scene. One Ball instance should be created at the position of the InstantiateCube moving towards the screen with some constant force provided by the physics component.

You may have to change the Z value depending on how you setup the cube position if the Ball is not moving in the correct direction as above.

  1. Try putting the code in step nine inside the InstatiateCube’s Update() function.
  1. Uncheck the Mesh Renderer to hide the InstantiateCube in the scene.
  1. Create a script called BallTidy and add the following to the Start() function:

Destroy(gameObject,5);

  1. Add the script to the Ball Prefab
  1. Run the Script the Ball should exist for 5 seconds.