C# Building Blocks: Variables

Mike Bischoff
3 min readApr 8, 2021
Photo by phil sheldon ABIPP on Unsplash

Arguably, the most important component in programming is also one of the most basic: variables.

Variables represent specific data types that can change dynamically over the course of your program, either by input fed in by the user or other processes within the program. They’re essentially storage containers, and every type of data requires the correct container.

Declaration of global variables

Data Types

Some of the common C# data types we’ll encounter most often are among the following:

  • int — Non-decimal integer that can be either positive or negative (referred to as “signed”)
  • long — 64-bit signed non-decimal integer for values exceeding int limits
  • float — Signed 16-bit floating point decimal number
  • string — Text encapsulated within quotation marks
  • bool — Two-value data type that can only be either true (on) or false (off)

In addition to signed types, there are also unsigned types such as uint, ulong, etc. (but not ufloat, which is unsupported in the .NET standard) which store only positive results.

You can read more about C# data types here.

This declaration will let us assign a GameObject as a variable in the inspector

We’re not limited to the built-in data types, however. Unity gives us the ability to use just about any component or GameObject as a variable, opening up tons of possibilities and extensibility for our programs later on.

Think Local, Script Global

Since the bool is contained within the method, it can only be used by that method

Depending on where you declare your variables, they will either be accessible globally within the entire class or locally within a specific method. While there’s no specific drawback to declaring all of your variables globally, it can improve the readability of your code to have method-specific variables declared inside the method they pertain to.

Protecting Your Data (Types)

All variables default to private unless you explicitly declare them public (though you also explicitly declare them as private, as well). The best practices standard is to keep all of your variables private, so other scripts and classes won’t be able to directly access and modify them (we’ll discuss this more when we talk about Script Communication).

Serialized variables in the inspector

In Unity, however, we frequently want some of our global variables to be accessible in the inspector and making them private prevents this. There is a handy workaround for this, we simply have to precede the variable declaration with [SerializeField] in square brackets. This displays the variable in the Inspector without affecting its privacy.

Note that local variables cannot be serialized and will need to be changed to global variables if you want to access them in the inspector.

--

--

Mike Bischoff

Author, motion designer, Unity developer, my producers’ favorite freelancer