Implementing Basic Arithmetic Operations in Unity Code
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:
Addition
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 into 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 attaching this script to a GameObject in Unity Scene and running the game, the arithmetic operations will be performed, and the results will be printed to the console. The values of num1 and num2 can be modified to test different calculations.