Answer the question
In order to leave comments, you need to log in
The script does not work - the calculator in the unit. What to do?
I made a simple calculator in the unit, but when you enter numbers in the input Field and click on the output button, either the number 2, or the number 1, or even zero comes out. For example, if you write 10 * 10, then 1 will come out, if you write 2 + 2, then 2 will come out, well, you understand.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Simplecalcan : MonoBehaviour
{
[SerializeField] InputField firstnum;
[SerializeField] InputField secondnum;
[SerializeField] InputField thesign;
[SerializeField] Text text;
public void Calculator()
{
if (thesign.text == "*")
{
int firstnum2 = Convert.ToInt32(firstnum);
int secondnum2 = Convert.ToInt32(secondnum);
int rezult = firstnum2 * secondnum2;
string rezult2 = rezult.ToString();
text.text = rezult2;
}
else if (thesign.text == "+")
{
int firstnum2 = Convert.ToInt32(firstnum);
int secondnum2 = Convert.ToInt32(secondnum);
int rezult = firstnum2 + secondnum2;
string rezult2 = rezult.ToString();
text.text = rezult2;
}
else if (thesign.text == "/")
{
int firstnum2 = Convert.ToInt32(firstnum);
int secondnum2 = Convert.ToInt32(secondnum);
int rezult = firstnum2 / secondnum2;
string rezult2 = rezult.ToString();
text.text = rezult2;
}
else if (thesign.text == "-")
{
int firstnum2 = Convert.ToInt32(firstnum);
int secondnum2 = Convert.ToInt32(secondnum);
int rezult = firstnum2 - secondnum2;
string rezult2 = rezult.ToString();
text.text = rezult2;
}
}
}
Answer the question
In order to leave comments, you need to log in
And here is the working shortened code. It is not the InputField component that needs to be converted, but the text of this component.
You can also use int.Parse(value).
using System;
using UnityEngine;
using UnityEngine.UI;
public class SimpleCalculator : MonoBehaviour
{
[SerializeField] private InputField _firstInput;
[SerializeField] private InputField _secondInput;
[SerializeField] private InputField _signInput;
[SerializeField] private Text _text;
// Methods
public void Calculator()
{
int a = int.Parse(_firstInput.text);
int b = int.Parse(_secondInput.text);
_text.text = GetResult(a, b).ToString();
}
private float GetResult(int a, int b)
{
switch(_signInput.text)
{
case "+": return Add(a, b);
case "-": return Substract(a, b);
case "*": return Multiply(a, b);
case "/": return Divide(a, b);
default: throw new Exception("Invalid sign");
}
}
private float Add(int a, int b) => a + b;
private float Substract(int a, int b) => a - b;
private float Multiply(int a, int b) => a * b;
private float Divide(int a, int b) => a / b;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question