C# Programming for Unity Fundamentals

C# Programming for Unity Fundamentals
Photo by Mohammad Rahmani / Unsplash

If you've dabbled around at all in Unity, you'll come across the language C#.

Note: this is a fluid document that I will continue to update as time goes on. Last update is June 3rd, 2022. Feel free to bookmark!

Additionally, if you are a little more advanced, C# Corner has a great reference article as well.

What is C#?

C# is an object-oriented language created by Microsoft, and is the primary language used to develop games in Unity.

It's often described as C++ lite.

C# and programming for games can be very daunting, but I'm here to break down some of the confusion.

C# Basic Terminology

Let's get the basics of C# out of the so we can get into the juicy stuff. Below is a list of the fundamental building blocks of C#.

Method:

A written command, aka a function. A set of instructions that execute something. A task, if you will.

Variables:

Containers that hold data.

Accessors:

These describe how and where something can be used.

public: allows other classes to access this variable. Also will show up in the Unity editor.

private: restricts access to this variable. Will not show up in the Unity editor.

void: means that this will not return anything. No data coming in or out.

Arrays

A list of sorts. I like to think of it as a wall of lockers, each locker being a slot for containing data.

Types of Data

data types:
int (integer, whole number)
bool (boolean, true or false)
float (decimal number 1.0, 1.2. value will always end in an f ex: 10f)

Assignment Operators

Assignment Operators assign data to variables.

+ 
- 
* 
/ 
+= 
-+ 
*= 
/=
%=

speed = speed + y (is the same as) speed+=y


%= (the remainder of something)

7 % 3 = 1 (because 3 goes into 7 twice, only 1 is leftover)

Comparison Operators

==  is equal to

!== is not equal to

< Less than
<= Less than or equal to

> Greater than
>= Greater than or equal to

Logical Operators

&& if this and this are equal to this, do something
|| if this or this are equal to this, do something
! if something is not this, do something

Unity Built-In Scripting Reference

This is something that confused the bejeezus out of me when I first got into game development. You'll be scrolling along Youtube, watching tutorials, and you'll see developers write code that they seemingly haven't written logic for, and yet it works.

Enter, the Unity Scripting API. Unity has a huge library of built-in scripts that you can access at any time by using their API.  When you see developers calling functions out of thin air this is a good place to start. Additionally, if you're getting stuck on a problem or don't want to break your back writing logic, have a search and see what you can find!

Happy coding!