What are Operators?
Operators are symbols or keywords that perform operations on variables and values. You are already using them, maybe without realizing it.
int score = 10 + 5;In this example, + is an operator that adds two values together.
Types of Operators in C#
C# has several groups of operators. Let’s break them down:
Arithmetic Operators
These are used for basic math:
// OPERA. | NAME | EXAMPLE | RESULT
//________|__________|___________|____________|
// + |Addition | a + b | Adds values|
// - |Subtract. | a - b | Subtracts |
// * |Multiplic.| a * b | Multiplies |
// / |Division | a / b | Divides |
// % |Modulus | a % b | Remainder |
Examples in Unity:
Addition (+)
int coins = 10;
int bonus = 5;
int total = coins + bonus;
Debug.Log("Total Coins: " + total);
// Output: 15
Subtraction (-)
int health = 100;
int damage = 25;
int remainingHealth = health - damage;
Debug.Log("Remaining health: " +
remainingHealth);
// Output: 75
Multiplication (*)
int baseScore = 10;
int multiplier = 3;
int finalScore = baseScore * multiplier;
Debug.Log("Final Score: " +
finalScore);
// Output: 30
Division (/)
float distance = 100f;
float time = 20f;
float speed = distance / time;
Debug.Log("Speed: " + speed);
//Output: 5
Modulus (%)
The modulus operator gives the remainder when one number is divided by another.
5 / 2 // remainder is 1
5 % 2 == 1
8 / 3 // remainder is 2
8 % 3 == 2
12 / 4 // remainder is 0
12 % 4 == 0
Some examples of how this might be used:
int number = 7;
if (number % 2 == 0)
{
Debug.Log(number + " is Even.");
}
else
{
Debug.Log(number + " is Odd.");
}
// Output: 7 is Odd.
/*
7 / 2 has a remainder of 1
Therefore 7 % 2 == 1
The remainder of any even
number / 2 will equal 0
*/
Creating circular index with modulus–
Useful in games when you cycle through options:
string[] weapons = { "Sword", "Bow", "Axe" };
int currentIndex = 5;
string selectedWeapon = weapons[currentIndex %
weapons.Length];
Debug.Log("Selected Weapon: " +
selectedWeapon);
/*
Output: "Selected Weapon: Axe"
(because 5 % 3 = 2, weapons[2] = "Axe"
*/
Assignment Operators
Used to assign or modify values in variables:
// OPERATOR | EXAMPLE | MEANING
//__________|__________|______________________|
// = | a = 2 | assign 10 to a |
// += | a += 2 | same as "a = a + 2" |
// -= | a -= 2 | same as "a = a - 2" |
// *= | a *= 2 | same as "a = a * 2" |
// /= | a /= 2 | same as "a = a / 2" |
// %= | a %= 2 | same as "a = a % 2" |
Examples in Unity:
Basic Assignment (=)
int score = 100;
Debug.Log("Score: " + score);
// Output: Score: 100
Add and Assign (+=)
int coins = 10;
coins += 5; // same as: coins = coins + 5;
Debug.Log("Coins: " + coins);
//Output: Coins: 15
Subtract and Assign (-=)
int health = 100;
health -= 20; // same as: health = health - 20;
Debug.Log("Health: " + health);
// Output: Health: 80
Multiply and Assign (*=)
int points = 10;
points *= 3; // same as: points = points * 3;
Debug.Log("Points: " = points);
// Output: Points: 30
Divide and Assign (/=)
int ammo = 60;
ammo /= 2; // same as: ammo = ammo / 2;
Debug.Log("Ammo: " + ammo);
// Output: Ammo: 30
Comparison (Relational) Operators
Used to compare values, returning true or false:
// OPERATOR | EXAMPLE | MEANING
//__________|_________|_______________________|
// == | a == b | Equal to |
// != | a != b | Not equal to |
// > | a > b | Greater than |
// < | a < b | Less than |
// >= | a >= b | Greater than or equal |
// <= | a <= 2 | Less than or equal |
Examples in Unity:
Not equal to (!=)
int health = 75;
if (health != 100)
{
Debug.Log("Player is not at full health.")
}
Equal to (==)
int score = 100;
if (score == 100)
{
Debug.Log("Perfect Score!")
}
Greater than (>)
int enemiesKilled = 10;
if (enemiesKilled > 5)
{
Debug.Log("You're on a killing spree!")
}
Less than (<)
int ammo = 3;
if (ammo < 5)
{
Debug.Log("Low ammo! Find more bullets.");
}
Less than or equal to (<=)
if (health <= 0)
{
Debug.Log("Game Over!"):
}
Greater than or equal to (>=)
int coins = 100;
if (coins >= 100)
{
Debug.Log("You can buy the item!");
}
Logical Operators
Used to combine true/false conditions (booleans)
// OPERATOR | EXAMPLE | MEANING
//__________|_________|____________________________|
// && | a && b | True only if both are true |
// || | a || b | True if either are true |
// ! | !a | Reverses true/false |
Examples in Unity
AND (&&)
Returns true only if both conditions are true.
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
Jump();
}Only jumps if the character is grounded and the space key is pressed.
OR (||)
Returns true if at least one condition is true.
if (health <= 0 || isDead)
{
Die();
}Triggers death if health is zero or if the player is flagged as already dead.
NOT (!)
Negates the condition
if (!isPaused)
{
Time.timeScale = 1f;
}Unpauses the game only if it’s not currently paused.
XOR (^)
Returns true if only one of the conditions is true, but not both.
bool toggle = optionA ^ optionB;toggle is true if only one of optionA or optionB is true.
Combination
if (doorLocked)
{
if (hasKey || overrideAccess)
{
doorLocked = false;
OpenDoor();
}
else
{
Debug.Log("Door is locked.");
}
}
else
{
OpenDoor();
}If the door is locked, but you have the key or the override access code you can open the door. Or if the door isn’t locked you can open the door.
Increment & Decrement Operators
// OPERATOR | EXAMPLE | MEANING
//__________|_________|____________________|
// ++ | a++ | add 1 to a |
// -- | a-- | subtract 1 from a |
++ is the same as saying a = a + 1 . Also the same as a += 1.
— is the same as saying a = a – 1. As well as a -= 1.
Examples in Unity
score++; // adds one point to the scoreor inside a loop:
for (int i = 0; i < 5; i++)
{
Debug.Log(i);
}