# Implementing Basic Arithmetic Operations in Unity Code

0 Comments · May 18, 2023
19

In the example below, we have a script called ArithmeticOperationsExample that performs basic arithmetic operations on two numbers, num1, and num2.

``````using UnityEngine;

public class ArithmeticOperationsExample : MonoBehaviour
{
void Start()
{
int num1 = 10;
int num2 = 5;

int sum = num1 + num2;
Debug.Log("Sum: " + sum);

// Subtraction
int difference = num1 - num2;
Debug.Log("Difference: " + difference);

// Multiplication
int product = num1 * num2;
Debug.Log("Product: " + product);

// Division
float quotient = (float)num1 / num2;
Debug.Log("Quotient: " + quotient);

// Modulus (Remainder)
int remainder = num1 % num2;
Debug.Log("Remainder: " + remainder);
}
}``````

Here's what each operation does:

The + operator adds num1 and num2, and the result is stored in the sum variable.
The sum is logged to the Unity console using Debug.Log()

## Subtraction

The - operator subtracts num2 from num1, and the result is stored in the difference variable.
The difference is logged to the Unity console.

## Multiplication

The * operator multiplies num1 by num2 and the result is stored in the product variable. The product is logged to the Unity console.

## Division

num1 is divided by num2 using the / operator. To get a float result instead of an integer, we cast num1 to float before dividing.
The quotient is stored in the quotient variable and logged to the console.

## Modulus (Remainder)

The % operator calculates the remainder of num1 divided by num2, and the result is stored in the remainder variable. The remainder is logged to the Unity console.

## Conclusion

When you attach this script to a GameObject in your Unity scene and run the game, the arithmetic operations will be performed, and the results will be printed to the console. You can modify the values of num1 and num2 to test different calculations.

We have a more in-depth article explaining all C# operators:

Unity C# Must-Know Operators

You Do Not Have To Do Everything Yourself
Search from thousands of ready-to-use Unity assets.