Programming in Unity C# - Part 2
Sometimes you need to have a formula that works for any given number. Or you need to be able to keep track of the player’s health. In order to do this, you will need a variable of one of the data types I mentioned in the last post.
If you want to keep track of player health, integers are a good way to go. But you can’t just expect the computer to know what you’re talking about when you say “Make the players health be less now, he got damaged.”
First, you need to tell the computer what the variable is called, and what the data type is.
The semicolon is like a period for the computer, separating two commands like a real period separates ideas. You need one at the end of almost every line.
You also need to tell the computer what the variable starts at. You have two options for this, both of the following variables will work fine;
If you don’t tell the computer what the variable starts at, each data type has a default value. int = 0; float = 0f; bool = false; string = ““;
Integers and floats don’t play nicely, so you can’t add them up normally. In order to add them up, you’ll have to use a cast. Casts are a way of turning one datatype into another, but only comparable data types will work. Strings and floats, for example, can’t be cast. To cast something put the data type you want in parenthesis in front of the variable.
int damage = (int)attack + strength;
Notice that the damage variable starts with a value of 15.
To be continued, with string addition and a word on booleans.