Reputation: 633
I'm building a simple calculator app in unity. My variable firstNumber is assigned a value but is getting set to zero when the Equal method is called. I can't figure out what is setting it back to zero. I've added a screenshot of the Unity Console to help explain.
private TextMesh inputBox;
private double firstNumber;
private char operation = '+';
void Start()
{
inputBox = (TextMesh)GameObject.Find("InputBox").GetComponent<TextMesh>();
}
public void nOne()
{
if (inputBox.text == "0" && inputBox.text != null)
{
inputBox.text = "1";
}
else
{
inputBox.text += "1";
}
}
public void Add()
{
firstNumber = double.Parse(inputBox.text);
Debug.Log("First num " + firstNumber);
operation = '+';
Debug.Log(operation);
inputBox.text = "0";
}
public void Equal()
{
double secondNumber;
double result;
Debug.Log("First Number: " + firstNumber);
secondNumber = double.Parse(inputBox.text);
Debug.Log("Second Number: " + secondNumber);
result = firstNumber + secondNumber;
Debug.Log("Sum: " + result);
}
Upvotes: 0
Views: 713
Reputation: 92
You are initializing the text field with zero and whenever it is called the result becomes zero
Upvotes: 0
Reputation: 10764
My first guess is that you're actually creating a new instance of your calculator object. firstNumber
would take its default value of zero on the new instance.
You can check if that is the case by using the "make object ID" functionality if using visual studio. Alternatively you can use a technique such as described here: How to print object ID? to check if they are in fact the same object instance.
I'm not familiar with the unity engine itself but I would not be surprised if some sort of binding code is responsible for generating the new instance.
Upvotes: 1
Reputation: 789
You have to remove or change it's position of inputBox.text = "0";
from Add() method. You are setting variables to 0 mistakenly
Upvotes: 1