Most tutorials online on creating calculators in the Unity Editor consist of you having to create a dedicated scene for that tool. Nothing wrong with this, but if you plan to use it, you are required to constantly switch between the scenes of your project and the calculator to do math problems, which is not the most practical process.

What if there was a way to use that same calculator, but it is directly integrated into the Unity Editor?

No scene switching! Just there when you need it.

The way you can do this is by utilizing a powerful tool within the Unity Editor called Editor Windows.

The ability to create your tools within the Unity Editor and extend the functionality of the Editor is often an overlooked or forgotten feature by Developers. Yet they can be used to create very helpful functionality within the Unity Editor.

Sound Interesting? I will be walking you through:

  • Integrating an Editor Window into the Unity Editor
  • Creating and positioning elements on the Editor Window
  • Correctly scaling elements when you resize the window
  • Calculator Functionality

Script Setup

When you are creating the C# script for an Editor Window, I would suggest having a folder dedicated to the Editor Window you are working on. This is because multiple scripts in the same folder operating as Editor Window Scripts will each apply its code to the same Editor Window, and not make new Windows. So if you want to create multiple Editor Window, separate them into their own folders.

So, add a new C# script called Calculator.cs to the folder you created for the editor window. Once in your Code Editor, you want to change two things about the script to give it the ability to create these Editor Windows:

  • Add the namespace using UnityEditor
  • change the class from MonoBehaviour to EditorWindow.

You don’t need the Start and Update methods for an Editor Window Script, so you can just delete them.

Before we can start writing the functionality of the Editor Window, we need a way to open it within the Unity Editor. You can do it by writing a simple method and referencing it to the Editor.

Create a Public Static Method within the class called ShowWindow:

public static void ShowWindow() 
{ 
}

Within that method, you will write a line of code that will open the Editor Window. Type GetWindow, reference the name of the script within <>, and name the editor window between Parenthesis and Quotation Marks:

public static void ShowWindow() 
{ 
	GetWindow<Calculator>("Calculator");
}

The ShowWindow method also works as a Start method equivalent, because the ShowWindow method will run upon opening the Editor Window.

Next will be a reference to it in the Editor menu.

Select the line right above your ShowWindow method, and write this line of code which will allow the Editor Window to be opened from the Unity Editor:

[MenuItem("Editor Windows/Calculator")]

The string “Editor Windows/Calculator” is the menu item that will display our window.

Now you can see that if we go back to the Unity Editor, there is a reference to our Editor Window, and it can be opened!

When we click on the button to open it, there is currently nothing on the Window itself, but there will be soon.

First Element

Going back into your Code Editor, there is a pre-existing method that comes with the EditorWindow Class. That method is OnGUI. This is a method that will automatically run anytime the Editor Window is rendered on screen or interacted with. This is the equivalent of the Update method.

Go to a line that is below the ShowWindow method, and create a private method called OnGUI. Anything inside this method is where the functionality of the Editor Window will come from.

private void OnGUI() 
{ 
}

Within the OnGUI Method, write this line of code.

GUI.Box(new Rect(0, 0, 20, 20), display);

GUI is a class used to create a specified GUI Element on the Editor Window. GUI‘s Box() method will display a box onto the Editor Window. It requires two parameters:

  • A Rect struct which contains the position and size of the box. We create it using the new Rect(0, 0, 20, 20) statement. The four values are the box’s x, y, width, and height in that order. For demonstrative purposes, we will define them to be 0, 0, 20, 20.
  • A string that contains the text to display on the box. We will use a variable of type string called display, initialized to “0”. So, at the top of the script, define the variable:
string display= "0";

We can go back to the Unity Editor and see that the Box is there. Just when we drag the corners of the Editor, the box doesn’t scale. The design we are going for is one that will scale with the size of the Editor Window.

Calculator User Interface and Scaling

Going back to our code editor, we need to create two new variables of type float. They’ll be named windowWidth and windowHeight.

float windowWidth; 
float windowHeight;

Within our OnGUI Method, just above the Box code, we will make the windowWidth variable equal to the width of the Editor Window, and the same for the windowHeight equaling the height of the Editor Window.

private void OnGUI() 
{ 
	windowWidth = position.width; 
	windowHeight = position.height; 
	GUI.Box(new Rect(0, 0, 20, 20), display); 
}

Before we can use these variables, there are two more that we need. They’ll be named dividedWidth and dividedHeight. We’ll need them to lay out all the elements that we will create shortly.

float dividedWidth; 
float dividedHeight;

In the OnGUI method , in the lines below the windowWidth and windowHeight value assignments, but still above the Box code, we will define these as windowWidth or windowHeight divided by the number of rows or columns. For this calculator layout, there will be 4 rows and 7 columns:

private void OnGUI() 
{ 
	windowWidth = position.width; 
	windowHeight = position.height; 
	dividedWidth = windowWidth / 4; 
	dividedHeight = windowHeight / 7; 
	GUI.Box(new Rect(0, 0, 20, 20), display); 
}

We will only be dividing the box by height, not width. So we will edit the Rect of the Box in such a way that the width is the same as the one of the editor window, and the height will be equal to the divided height:

GUI.Box(new Rect(0, 0, windowWidth, dividedHeight), display);

Now, it is time to create the buttons for user input.

The position of each button will be dividedWidth and dividedHeight multiplied by its position relative to the number of rows or columns, and their size will be dividedWidth × dividedHeight. Each button will have an icon to represent its function.

The code to create a button will look something like this:

if (GUI.Button(new Rect(0, dividedHeight * 5, dividedWidth, dividedHeight), "1")) { }

This code would go in the lines right below the GUI.Box code.

But because you probably don’t want to do that 23 more times, right below is the code for all 24 buttons and some special characters included:

if (GUI.Button(new Rect(0, dividedHeight * 1, dividedWidth, dividedHeight), "π")) { } 
if (GUI.Button(new Rect(0, dividedHeight * 2, dividedWidth, dividedHeight), "1/x")) { } 
if (GUI.Button(new Rect(0, dividedHeight * 3, dividedWidth, dividedHeight), "7")) { } 
if (GUI.Button(new Rect(0, dividedHeight * 4, dividedWidth, dividedHeight), "4")) { } 
if (GUI.Button(new Rect(0, dividedHeight * 5, dividedWidth, dividedHeight), "1")) { } 
if (GUI.Button(new Rect(0, dividedHeight * 6, dividedWidth, dividedHeight), "0")) { } 
if (GUI.Button(new Rect(dividedWidth, dividedHeight * 1, dividedWidth, dividedHeight), "CE")) { } 
if (GUI.Button(new Rect(dividedWidth, dividedHeight * 2, dividedWidth, dividedHeight), "x²")) { } 
if (GUI.Button(new Rect(dividedWidth, dividedHeight * 3, dividedWidth, dividedHeight), "8")) { } 
if (GUI.Button(new Rect(dividedWidth, dividedHeight * 4, dividedWidth, dividedHeight), "5")) { } 
if (GUI.Button(new Rect(dividedWidth, dividedHeight * 5, dividedWidth, dividedHeight), "2")) { } 
if (GUI.Button(new Rect(dividedWidth, dividedHeight * 6, dividedWidth, dividedHeight), ".")) { } 
if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 1, dividedWidth, dividedHeight), "C")) { } 
if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 2, dividedWidth, dividedHeight), "x³")) { } 
if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 3, dividedWidth, dividedHeight), "9")) { } 
if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 4, dividedWidth, dividedHeight), "6")) { } 
if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 5, dividedWidth, dividedHeight), "3")) { } 
if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 6, dividedWidth, dividedHeight), "=")) { } 
if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 1, dividedWidth, dividedHeight), "⌫")) { } 
if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 2, dividedWidth, dividedHeight), "²√x")) { } 
if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 3, dividedWidth, dividedHeight), "÷")) { } 
if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 4, dividedWidth, dividedHeight), "×")) { } 
if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 5, dividedWidth, dividedHeight), "-")) { } 
if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 6, dividedWidth, dividedHeight), "+")) { }

If we check the Editor Window, the user interface is all finished! We can drag the corners of the Editor Window, and all the Elements will scale properly with it.

Digit Input

Now it’s time to implement the calculator functionality.

We will create two methods that take string parameters: one for entering digits, and one for entering operators. Future code modifications will require these methods to be separated.

private void DigitPushed(string digit) 
{ 
	display += digit; 
} 

private void OperatorPushed(string operation) 
{ 
	display += operation; 
}

Go to the OnGUI method and apply the correct methods to the proper buttons for both the digits (1 – 9 and the dot “.”) and the operators (+, -, ×, ÷). Here are two examples:

// Code for the 1 button
if (GUI.Button(new Rect(0, dividedHeight * 5, dividedWidth, dividedHeight), "1"))
{ 
	DigitPushed("1"); 
}

// Code for the + button
if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 6, dividedWidth, dividedHeight), "+"))
{ 
	OperatorPushed("+"); 
}

Once you do that for all the correct buttons, we can enter an expression within the calculator:

Removing Digits

Now the backspace function. Create a method called RemoveDigit and write this code within it:

Private void RemoveDigit()
{ 
	display = display.Substring(0, display.Length - 1);
}

Substring removes a defined amount of characters from the beginning or end of a string.

Before we can say this method is finished, we need an if statement in the lines above the Substring code, to prevent the number of characters in the display from going at or below zero:

private void RemoveDigit() 
{ 
	if (display.Length - 1 <= 0) 
	{ 
		display= "0"; 
		return; 
	} 
	display = display.Substring(0, display.Length - 1); 
}

Now we can apply the RemoveDigit method to the backspace button, and the functionality in the editor window checks out too.

Calculate Answer

Now we need to create a method to put the inputs together with the correct operation:

private void CalculateAnswer() 
{ 
}

At the top of the class, we need to create two lists, used to hold the characters for the digits and the operators. These are required so that the calculator can tell the difference between digits and operators.

List<char> digits = new List<char>(11) { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' }; 
List<char> operators = new List<char>(4) { '+', '-', '×', '÷' };

At the beginning of the CalculateAnswer method, create these variables to save data throughout the calculation:

string entry = string.Empty;
int expressionLength = display.Length;
List<float> expressionEntries = new List<float>();
List<char> expressionOperators = new List<char>();
int mdNumber = 0;

The calculator will determine the answer using some for loops. The first for loop will be used to differentiate the entries from the signs and save them in the correct order to use later. Also, it save the number of times an × or ÷ operator appears.

for (int x = 0; x < expressionLength; x++) 
{ 
	if (digits.Contains(display[0])) 
	{ 
		entry += display[0].ToString(); 
		if (display.Length == 1) 
			expressionEntries.Add(float.Parse(entry, System.Globalization.CultureInfo.InvariantCulture)); 
	} 
	else if (operators.Contains(display[0])) 
	{ 
		if (display[0] == '×' || display[0] == '÷') 
			mdNumber++; 
		expressionEntries.Add(float.Parse(entry, System.Globalization.CultureInfo.InvariantCulture)); 
		expressionOperators.Add(display[0]); 
		entry = string.Empty; 
	} 
	display = display.Substring(1); 
}

The second for loop is here to help the expression conform to the Rules of the Order of Operations: doing multiplications and divisions before any addition or subtraction.

for (int y = 0; y < mdNumber; y++) 
{ 
	for (int w = 0; w < Mathf.Infinity; w++) 
	{ 
		float orderOfOperationResult; 
		if (expressionOperators[w] == '×') 
		{ 
			orderOfOperationResult = expressionEntries[w] * expressionEntries[w + 1]; 
			expressionEntries[w] = orderOfOperationResult; 
			expressionEntries.Remove(expressionEntries[w + 1]); 
			expressionOperators.Remove(expressionOperators[w]); 
			break; 
		} 
		else if (expressionOperators[w] == '÷') 
		{ 
			orderOfOperationResult = expressionEntries[w] / expressionEntries[w + 1]; 
			expressionEntries[w] = orderOfOperationResult; 
			expressionEntries.Remove(expressionEntries[w + 1]); 
			expressionOperators.Remove(expressionOperators[w]); 
			break; 
		} 
	} 
}

The third and final for loop will take the remaining entries and operators and add or subtract them together. Before the loop, a variable of type float is created to save the result.

float result = expressionEntries[0]; 
for (int z = 0; z < expressionOperators.Count; z++) 
{ 
	if (expressionOperators[z] == '+') 
		result += expressionEntries[z + 1]; 
	else if (expressionOperators[z] == '-') 
		result -= expressionEntries[z + 1]; 
}

Finish off the method by making the display equal to the result.

display = result.ToString();

Now apply the CalculateAnswer method to the Equal button. Returning to the Editor Window, we can input as many entries as we want, and the calculator will give us an answer.

Clearing Entries

Now let’s see the code for the buttons that we haven’t touched yet. These buttons will also be important because some have functions that you can’t get just from numbers and operators.

The C button will reset the entire display. The CE button will remove digits until it comes across an operator or the end of the string.

private void ClearAllEntries() // C 
{ 
	display = "0"; 
} 

private void ClearCurrentEntry() // CE 
{ 
	for (int x = 0; x < Mathf.Infinity; x++) 
	{ 
		if (operators.Contains(display[display.Length - 1])) 
			
		else if (display.Length - 1 == 0) 
		{ 
			display = "0"; 
			break; 
		} 
		else if (digits.Contains(display[display.Length - 1])) 
			display = display.Substring(0, display.Length - 1); 
	} 
}

Apply these methods to the correct buttons, and now two more are completed.

The Final Five Buttons

The remaining five buttons have methods that, for the most part, work by changing the value of the last entry.

Before creating the methods for those five buttons, we need two methods that contain code that would otherwise be repeated multiple times.

private float ReturnEndEntry() // find and return the entry at the end 
{ 
	string entryString = string.Empty; 
	for (int x = 0; x < display.Length; x++) 
	{ 
		entryString += display[x]; 
		if (operators.Contains(display[x])) 
			entryString = string.Empty; 
	} 
	float entry = float.Parse(entryString, System.Globalization.CultureInfo.InvariantCulture); 
	return entry; 
} 

private void ChangeEndEntry(float calculation) // apply the calculation 
{ 
	if (display == "0") 
	{ 
		display = calculation.ToString(); 
		return; 
	} 
	display += calculation.ToString(); 
}

Here’s the final functions of the calculator:

private void EnterPI() 
{ 
	ClearCurrentEntry(); 
	if (display == "0") 
		display = string.Empty; 
	display += "3.141593"; 
} 

private void CalculateTheSquareRoot() 
{ 
	float calculation = Mathf.Sqrt(ReturnEndEntry()); 
	ClearCurrentEntry(); 
	ChangeEndEntry(calculation); 
}

private void CalculateToThePowerOfTwo() 
{ 
	float calculation = Mathf.Pow(ReturnEndEntry(), 2); 
	ClearCurrentEntry(); 
	ChangeEndEntry(calculation); 
}

private void CalculateToThePowerOfThree() 
{ 
	float calculation = Mathf.Pow(ReturnEndEntry(), 3); 
	ClearCurrentEntry(); 
	ChangeEndEntry(calculation); 
} 

private void CalculateOver1() 
{ 
	float calculation = (1 / ReturnEndEntry()); 
	ClearCurrentEntry(); 
	ChangeEndEntry(calculation); 
}

Now, apply those methods to the correct buttons. So, EnterPI() goes with π, CalculateOver1() goes with 1/x, CalculateToThePowerOfTwo() goes with x², CalculateToThePowerOfThree() goes with x³, and CalculateTheSquareRoot() goes with the square root button.

Squashing Some Bugs

While you might think we are done, there are some final steps that we need to follow to prevent our calculator from doing things a calculator shouldn’t.

Add these variables at the beginning of the class:

bool enteredOperator = false; 
bool enteredDot = false;
bool resetUponDigitInput = false;

The first two variables will prevent multiple operators and dots from being placed one after another. The third boolean will be used to prevent a digit from being added to the end of an expression’s result.

Now, in the DigitPushed() method, we need to add a few if statements:

private void DigitPushed(string digit)
{
	if (resetUponDigitInput)
	{
		resetUponDigitInput = false;
		display = "0";
	}
	if (enteredDot == true && digit == ".")
		return;
	if (digit == ".")
		enteredDot = true;
	if (display == "0" && digit != ".")
		display = display.Substring(0, display.Length - 1);
	display += digit;
	enteredOperator = false;
}

OperatorPushed() will need a new if statement too:

private void OperatorPushed(string operation)
{
	if (enteredOperator == true)
		return;
	display += operation;
	enteredOperator = true;
	enteredDot = false;
	resetUponDigitInput = false;
}

RemoveDigit() will allow a dot to be pressed only if the previous one is deleted:

private void RemoveDigit()
{
	resetUponDigitInput = false;
	if (display.Length - 1 <= 0)
	{
		display = "0";
		return;
	}
	if (display[display.Length - 1] == '.')
		enteredDot = false;
	display = display.Substring(0, display.Length - 1);
}

Both ClearAllEntries() and ClearCurrentEntry() need this code at the bottom:

bool enteredOperator = false; 
bool enteredDot = false;
bool resetUponDigitInput = false;

Finally, we need to set resetUponDigitInput to true at the end of the CalculateAnswer(), EnterPI(), CalculateTheSquareRoot(), CalculateToThePowerOfTwo(), CalculateToThePowerOfThree() and CalculateOver1() methods:

resetUponDigitInput = true;

Now that further code has been used to prevent any incorrect behavior, we can now use the calculator in its entirety!

Click here to see the complete Calculator Script:

Calculator Script
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class Calculator : EditorWindow
{
    string display = "0";
    float windowWidth;
    float windowHeight;
    float dividedWidth;
    float dividedHeight;
    List digits = new List(11) { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' };
    List operators = new List(4) { '+', '-', '×', '÷' };
    bool enteredOperator = false;
    bool enteredDot = false;
    bool resetUponDigitInput = false;

    [MenuItem("Editor Windows/Calculator")]
    public static void ShowWindow()
    {
        GetWindow("Calculator");
    }

    private void OnGUI()
    {
        windowWidth = position.width;
        windowHeight = position.height;
        dividedWidth = windowWidth / 4;
        dividedHeight = windowHeight / 7;

        GUI.Box(new Rect(0, 0, windowWidth, dividedHeight), display);

        if (GUI.Button(new Rect(0, dividedHeight * 1, dividedWidth, dividedHeight), "π")) {
            EnterPI();
        }
        if (GUI.Button(new Rect(0, dividedHeight * 2, dividedWidth, dividedHeight), "1/x")) {
            CalculateOver1();
        }
        if (GUI.Button(new Rect(0, dividedHeight * 3, dividedWidth, dividedHeight), "7")) {
            DigitPushed("7");
        }
        if (GUI.Button(new Rect(0, dividedHeight * 4, dividedWidth, dividedHeight), "4")) {
            DigitPushed("4");
        }
        if (GUI.Button(new Rect(0, dividedHeight * 5, dividedWidth, dividedHeight), "1")) {
            DigitPushed("1");
        }
        if (GUI.Button(new Rect(0, dividedHeight * 6, dividedWidth, dividedHeight), "0")) {
            DigitPushed("0");
        }
        if (GUI.Button(new Rect(dividedWidth, dividedHeight * 1, dividedWidth, dividedHeight), "CE")) {
            ClearCurrentEntry();
        }
        if (GUI.Button(new Rect(dividedWidth, dividedHeight * 2, dividedWidth, dividedHeight), "x²")) {
            CalculateToThePowerOfTwo();
        }
        if (GUI.Button(new Rect(dividedWidth, dividedHeight * 3, dividedWidth, dividedHeight), "8")) {
            DigitPushed("8");
        }
        if (GUI.Button(new Rect(dividedWidth, dividedHeight * 4, dividedWidth, dividedHeight), "5")) {
            DigitPushed("5");
        }
        if (GUI.Button(new Rect(dividedWidth, dividedHeight * 5, dividedWidth, dividedHeight), "2")) {
            DigitPushed("2");
        }
        if (GUI.Button(new Rect(dividedWidth, dividedHeight * 6, dividedWidth, dividedHeight), ".")) {
            DigitPushed(".");
        }
        if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 1, dividedWidth, dividedHeight), "C")) {
            ClearAllEntries();
        }
        if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 2, dividedWidth, dividedHeight), "x³")) {
            CalculateToThePowerOfThree();
        }
        if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 3, dividedWidth, dividedHeight), "9")) {
            DigitPushed("9");
        }
        if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 4, dividedWidth, dividedHeight), "6")) {
            DigitPushed("6");
        }
        if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 5, dividedWidth, dividedHeight), "3")) {
            DigitPushed("3");
        }
        if (GUI.Button(new Rect(dividedWidth * 2, dividedHeight * 6, dividedWidth, dividedHeight), "=")) {
            CalculateAnswer();
        }
        if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 1, dividedWidth, dividedHeight), "⌫")) {
            RemoveDigit();
        }
        if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 2, dividedWidth, dividedHeight), "²√x")) {
            CalculateTheSquareRoot();
        }
        if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 3, dividedWidth, dividedHeight), "÷")) {
            OperatorPushed("÷");
        }
        if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 4, dividedWidth, dividedHeight), "×")) {
            OperatorPushed("×");
        }
        if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 5, dividedWidth, dividedHeight), "-")) {
            OperatorPushed("-");
        }
        if (GUI.Button(new Rect(dividedWidth * 3, dividedHeight * 6, dividedWidth, dividedHeight), "+")) {
            OperatorPushed("+");
        }
    }

    private void DigitPushed(string digit)
    {
        if (resetUponDigitInput)
        {
            resetUponDigitInput = false;
            display = "0";
        }
        if (enteredDot == true && digit == ".")
            return;
        if (digit == ".")
            enteredDot = true;
        if (display == "0" && digit != ".")
            display = display.Substring(0, display.Length - 1);
        display += digit;
        enteredOperator = false;
    }

    private void OperatorPushed(string operation)
    {
        if (enteredOperator == true)
            return;
        display += operation;
        enteredOperator = true;
        enteredDot = false;
        resetUponDigitInput = false;
    }

    private void RemoveDigit()
    {
        resetUponDigitInput = false;
        if (display.Length - 1 <= 0)
        {
            display = "0";
            return;
        }
        if (display[display.Length - 1] == '.')
            enteredDot = false;
        display = display.Substring(0, display.Length - 1);
    }

    private void CalculateAnswer()
    {
        string entry = string.Empty;
        int expressionLength = display.Length;
        List expressionEntries = new List();
        List expressionOperators = new List();
        int mdNumber = 0;

        for (int x = 0; x < expressionLength; x++)
        {
            if (digits.Contains(display[0]))
            {
                entry += display[0].ToString();
                if (display.Length == 1)
                    expressionEntries.Add(float.Parse(entry, System.Globalization.CultureInfo.InvariantCulture));
            }
            else if (operators.Contains(display[0]))
            {
                if (display[0] == '×' || display[0] == '÷')
                    mdNumber++;
                expressionEntries.Add(float.Parse(entry, System.Globalization.CultureInfo.InvariantCulture));
                expressionOperators.Add(display[0]);
                entry = string.Empty;
            }
            display = display.Substring(1);
        }

        for (int y = 0; y < mdNumber; y++)
        {
            for (int w = 0; w < Mathf.Infinity; w++)
            {
                float orderOfOperationResult;
                if (expressionOperators[w] == '×')
                {
                    orderOfOperationResult = expressionEntries[w] * expressionEntries[w + 1];
                    expressionEntries[w] = orderOfOperationResult;
                    expressionEntries.Remove(expressionEntries[w + 1]);
                    expressionOperators.Remove(expressionOperators[w]);
                    break;
                }
                else if (expressionOperators[w] == '÷')
                {
                    orderOfOperationResult = expressionEntries[w] / expressionEntries[w + 1];
                    expressionEntries[w] = orderOfOperationResult;
                    expressionEntries.Remove(expressionEntries[w + 1]);
                    expressionOperators.Remove(expressionOperators[w]);
                    break;
                }
            }
        }

        float result = expressionEntries[0];
        for (int z = 0; z < expressionOperators.Count; z++)
        {
            if (expressionOperators[z] == '+')
                result += expressionEntries[z + 1];
            else if (expressionOperators[z] == '-')
                result -= expressionEntries[z + 1];
        }

        display = result.ToString();
        resetUponDigitInput = true;
    }

    private void ClearAllEntries() // C
    {
        display = "0";
        enteredOperator = false;
        enteredDot = false;
        resetUponDigitInput = false;
    }

    private void ClearCurrentEntry() // CE
    {
        for (int x = 0; x < Mathf.Infinity; x++)
        {
            if (operators.Contains(display[display.Length - 1]))
                break;
            else if (display.Length - 1 == 0)
            {
                display = "0";
                break;
            }
            else if (digits.Contains(display[display.Length - 1]))
                display = display.Substring(0, display.Length - 1);
        }
        enteredOperator = false;
        enteredDot = false;
        resetUponDigitInput = false;
    }

    private float ReturnEndEntry() // find and return the entry at the end
    {
        string entryString = string.Empty;
        for (int x = 0; x < display.Length; x++)
        {
            entryString += display[x];
            if (operators.Contains(display[x]))
                entryString = string.Empty;
        }
        float entry = float.Parse(entryString, System.Globalization.CultureInfo.InvariantCulture);
        return entry;
    }

    private void ChangeEndEntry(float calculation) // apply the calculation
    {
        if (display == "0")
        {
            display = calculation.ToString();
            return;
        }
        display += calculation.ToString();
    }

    private void EnterPI()
    {
        ClearCurrentEntry();
        if (display == "0")
            display = string.Empty;
        display += "3.141593";
        resetUponDigitInput = true;
    }

    private void CalculateTheSquareRoot()
    {
        float calculation = Mathf.Sqrt(ReturnEndEntry());
        ClearCurrentEntry();
        ChangeEndEntry(calculation);
        resetUponDigitInput = true;
    }

    private void CalculateToThePowerOfTwo()
    {
        float calculation = Mathf.Pow(ReturnEndEntry(), 2);
        ClearCurrentEntry();
        ChangeEndEntry(calculation);
        resetUponDigitInput = true;
    }

    private void CalculateToThePowerOfThree()
    {
        float calculation = Mathf.Pow(ReturnEndEntry(), 3);
        ClearCurrentEntry();
        ChangeEndEntry(calculation);
        resetUponDigitInput = true;
    }

    private void CalculateOver1()
    {
        float calculation = (1 / ReturnEndEntry());
        ClearCurrentEntry();
        ChangeEndEntry(calculation);
        resetUponDigitInput = true;
    }
}

Did you enjoy this article? Then consider buying me a coffee! Your support will help me cover site expenses and pay writers to create new blog content.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to browse this Website, you consent to the use of cookies. More information

This Website uses:

By continuing to browse this Website without changing the cookies settings of your browser or by clicking "Accept" below, you consent to the use of cookies.

Close