0

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);

}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
FestiveHydra235
  • 473
  • 1
  • 7
  • 23

3 Answers3

1

You have to remove or change it's position of inputBox.text = "0"; from Add() method. You are setting variables to 0 mistakenly

PrathapG
  • 751
  • 1
  • 7
  • 21
1

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.

Nathan
  • 10,593
  • 10
  • 63
  • 87
  • I used a GetHash code to varify, and you are right. They are not the same object, its creating a new instance. But I'm not sure what to do with this. How would I fix it from creating a new instance? – FestiveHydra235 Jan 08 '19 at 07:59
  • Are you instantiating the object somewhere else? How are you calling your calculator code? – Eliasar Jan 08 '19 at 16:00
0

See the Image for the answer

You are initializing the text field with zero and whenever it is called the result becomes zero