4 - Intro to Coding
In this tutorial I will give you an introduction to how to write code in Unity. I will go over the different languages that are available in Unity's Monodevelop, but will focus primarily on C# for the rest of my coding. I'll wrap up the tutorial with an example of a hello world script.
To read more about MonoDevelop in general follow this link: http://www.monodevelop.com/
Unity utilizes a component based programming approach. This means that game objects have components that have a set of features attached to them rather than inheriting other objects. While this may be difficult to grasp at first, it is actually pretty handy when designing games. Spending a little time thinking about how things come together will help you make great choices in the end.
It is important when you are programming in Unity, to spend some time developing designs and workflow for your code. For instance, let's say we have a gameobject called player. What kind of features should our player have? Let's say the player will have health, attack, and speed. She will also be able to walk. So what are our options here for achieving this? Well, we could write one giant script which contains all of those features. However, if we decide we also want an enemy gameobject to have health, attack, and speed, but not movement we are SOL. However, if we have one script that defines those attributes and a separate script for movement, we can achieve our goal.
Here is a picture to help illustrate what I am talking about:
Cue revolutionary World Hello program. The thing to note with this program is that it is attached to a game object in your scene to run.
The two statements at the top are namespaces. Don't worry too much what that means right now, just know that they are giving you most of the stuff you need to run a script. Also note the : MonoBehaviour extension after World Hello. Every script that you want to attach to something in your game needs to have this extension. If you don't believe me, try removing it. Doesn't work, huh.
So what we have to the right is three variables that are being defined; health, speed, and defense. They are being initialized in the Start function, and the defense is being updated and logged every frame. To see the output in your console, make sure you attach it to an object in the scene!
Note that Hello and world do not show up in this tutorial. This is a World Hello tutorial, not a Hello World tutorial.