Sharp Coder is reader-supported, meaning when you buy through links on our site, we may earn an affiliate commission.

Implementing Basic Arithmetic Operations in Unity Code

0 Comments ยท May 18, 2023

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;

        // Addition
        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()


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


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


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.


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.
Visit Asset Store