Hey guys. So, I’m trying to make a sort of converter type deal. I am running into several issues. This is my first time integrating buttons and input fields, so bare with me.
I have 3 value. A, B, and C.
A is ALWAYS going to be required.
A will either be divided by B or by C.
If A is divided by B, then I’d like the results to appear in the C input box.
If A is divided by C, then I’d like the results to appear in the B input box.
For testing purposes, I’m kind of ignoring that part in my current scene setup. My main goal is just to have A / B = C. So far with my current code, it does not do this. The results aren’t even replacing the text within C’s text component. Here is my code
using System; // For Convert.ToInt
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Math : MonoBehaviour
{
public InputField A;
public InputField B;
public InputField C;
//public Text ResultB;
public Text ResultC;
public void Division ()
{
int a = Convert.ToInt32 (A);
int b = Convert.ToInt32 (B);
int c = a / b;
ResultC.text = c.ToString ();
}
}
Heres the UI setup
So what can I do to fix this? Is there a simpler way of approaching this? How would I make it so putting an input in either B or C will always display the answer in the appropriate input box?
Thanks for the help. I do have a button with the OnClick function set to start my Division function btw.
To change the text in the input field, try using the InputField.text value instead of the direct text reference.
As for the other part,
Something like should work, assuming I understood correctly:
public class Math : MonoBehaviour
{
public InputField A;
public InputField B;
public InputField C;
public void Division ()
{
// Access A.text, can't convert an input field itself to an integer.
int a = Convert.ToInt32(A.text);
int b, c;
// Try to convert B's text to an integer. If it works, input field B contains
// an integer. Divide a by b and store it in C.
if (int.TryParse(B.text, out b))
C.text = (a / b).ToString();
// Try to convert C's text to an integer. If it works, input field C contains
// an integer. Divide a by c and store it in B.
else if (int.TryParse(C.text, out c))
B.text = (a / c).ToString();
}
}
This doesn’t properly handle the case where both B and C may have integers or when neither has an integer, though. That depends on how you want to handle it.
Thanks! For the cases you mention, I think I could set up some special if statements to show errors! Can you TryParse is a new one… What are some other practical uses for it?
TryParse is what you use to convert a string that you expect to be an integer into an integer. Convert is more general and, as far as I’m aware, uses TryParse internally when it finds out that you’re trying to convert a string.
So, since you’re using strings here, you can just use TryParse.