Friday, 11 February 2011

Day 4 - Definitions, Variables and Random Numbers

Yesterday we created a GameObject, a Scene and a Script. Let's quickly look at the definition of these from the Unity site...

  • Scenes contain the objects of your game. They can be used to create a main menu, individual levels, and anything else. Think of each unique Scene file as a unique level. Scenes definition
  • GameObjects are the most important objects in Unity. It is very important to understand what a GameObject is. OH GREAT! ....and I wanted an easy day...GameObjects are containers. They are empty boxes which can hold the different pieces that make up[your game].BETTER! See here for full definition GameObjects definition
  • You can add additional functionality to your GameObjects by using Scripts. MAKES SENSE!
So using my limited knowledge so far I'd say .....a Game is made up of Scenes, a GameObject resides in a Scene and contains the main blocks of your game (i.e a Sphere/Ball). A script can bring this block to life by moving it about and crashing into a wall. WALLOP!

Enough about boring old definitions let's do something creative...

Using the Hello World example yesterday let's have a quick play with the script we created. Fire up Unity and open the example. Click on the scene and open up the script.

LET'S MAKE THINGS PERSONAL!  (You Stink! no! not like that!.....)

Change the code to the following:-  (new bits highlighted in BOLD)

var myName = "Unity Novice";
function OnGUI () {
    // Make a background box
    GUI.Box (Rect (10,10,100,40), myName);
}

You have created a variable here with your name in it and displayed it out to the screen.

Run the game (click the Play arrow) and you'll see your name (or mine if you forgot to put your name in!)

Now this may not be very exciting but trust me when I learned BASIC on the BBC Micro 30 years ago this is the sort of shit you'd get off on!

One thing about the scripts I wanted to discover is when and how often is OnGUI() called? Just once or every so often? I decided to combine a couple of quick experiments here to see.

All good games need random numbers so let's see how these are generated...

Change your script to...

var myName = "Henry VIII";
function OnGUI () {
    // create random Number from 0-100
    var myNum:int = Random.Range(0, 100);
    // display variables
    GUI.Box (Rect (10,10,100,40), myName);
    GUI.Box (Rect (10,50,100,40), myNum.ToString());
}

Now run it!

As you can see the random number changes every fraction of a second so we can deduce that OnGui() is called every frame or so. Nice.

Please note that the random number is an integer and needs converting to a string before being displayed using ToString()

That is enough excitement for now. Have a play with the scripts and see where you get. Try adding more boxes and maybe a button! 

No comments:

Post a Comment