Part 2: Writing Scripts for Unity

This post follows: Part 1: Going beyond the Virtual Block Sandbox

In the preceding post, we discussed setting up a basic 3D scene. Unity simplifies a significant portion of the graphics display effort, handled typically through the Unity Editor. To make things “go” we need to write scripts.

Before we start designing the scripts for our Mars Base Project, I’ll cover writing a simple script that we’ll attach to an object. We’ll create a scene with a cube and then write a simple script to rotate that cube.

Video Summary Notes

  • Create a new scene in our project and then create a cube
  • With the cube selected, pressing “F” on the keyboard will focus the scene view on the cube
  • The Game View is based on what the camera “sees”, you can use the Scene View as guide for the camera, select the Camera and press “CTRL-SHIFT-F” and the camera view will match the Scene
  • Create a folder to organize our files (except for a few specific folder conventions, the folder name and structure is a user preference)
  • Right-click inside the script folder to generate the script base and rename to something like “RotateMe” since we’re attaching it to an object that will be rotated
  • Double click the script to edit. This will open Visual Studio (instead of MonoDevelop) since my workstation is configured with Visual Studio Tools for Unity
  • The script defines a class derived from “MonoBehavior” and has a method “Update()” which is called by the Unity Runtime every graphics display frame update
  • Edit the Update() method and include the line:

transform.Rotate(Vector3.up * Time.deltaTime * 90f);

  • “transform” is the transform of the GameObject of the script, in our example that’s the position and orientation/rotation of the cube in our scene world space
  • We tell the Rotate() method to rotate about the Y-axis (Vector3.up) at the rate of 90 degrees per second. We’re able to adjust the rotation rate on the Update() as Time.deltaTime provides us with the time elapsed from the last update to the current call.

Now that we’ve seen what scripts do in a Unity project, we’re going back to our Mars Base Sample Project. Based on the design concept, we need to manage 4 resource items Air, Water, Food and Power which gets consumed and also created over time so instead of just action methods we would have to also manage and control system states. I’ll discuss this design and implementation on the next entry.

For questions, comments or contact – follow me on Twitter @rlozada

Next: Part 3: Creating the Game State Management Script