Journal 05 — C# Programming, Basics of Variables

In programming for games or applications, variables are used to store information. Variables generally consist of the following types:

string — a series of text, but can also contain a combination of numbers, characters, and spaces. Could also be a type char, which is just one character

int — a whole number, with no decimal

bool — true or false status

float — number including decimal

For additional info, see this description: C# Variables (w3schools.com)

For a simple example, I’ll attach a C# script to a cube and fill in some variables in Unity and show some ways they can be used.

In Unity, you need four pieces of information to declare a variable:

public or private — declares the variable to either display for viewing and editing, or make it accessible to other methods in the project

type — as described above, the type of data to store

name — the name of your variable.

stored info

I’ll add some variables in the C# script, and see what they look like in Unity:

Unity C# Variables (all Public type)
Unity Inspector (all Public variables are visible)

Next I’ll change a few of the entries to private and see what happens in Unity:

Unity C# Variables (Public and Private types)
Unity Inspector (only Public variable visible in the Inspector)

Let’s add some other variables related to Unity that can modify the player, in this case a cube. I’ll access the transform of the Player to change its position, rotation, and scale at the start of Play.

Unity C# new variables declared
Unity C# Start Method changes
Unity, see changes at start of Play

If you want to modify some values in real time, move the code to the Update method, and modify the values in the Inspector during Playmode.

Unity C# move transform commands to Update method
Unity, see changes and modify in realtime during Play

I have some additional ideas on different uses of variables, but that should go in its own post for another time.

Thanks for stopping by!

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.