I am creating an app that needs to take the variable input from one input field UI box, then take the variable from the other box, and multiply them together to create an answer that shows up on the screen when a button is clicked.
I am unsure of the proper calling for the functions because when i look at the input field functions this website comes up: http://docs.unity3d.com/ScriptReference/UI.InputField.html
It has everything i need except i cant find basic functions such as addition and multiplication as well as how to call an input field to be used.
If you have some sample code of how to do this, it would be much appreciated. JS is preferred for me but i know C# as well.
If you have any questions please feel free to ask. I may have not made my question clear enough.
InputFields contain a string text even if you set it to only admit numbers, so you have to start from there.
Also, InputFields are just that, a field where you can input something, adding and multiplying it’s content is not part of their functionality.
To do math operations you have to take the text string from both InputFields (the “text” property) then parse an integer or decimal value from it (How to: Convert a String to a Number (C# Programming Guide) | Microsoft Learn) and then make the operation with the common math operators.
Once you have the result you have to turn the number value into a string again (the ToString method) and set it as the “text” property of the Text component where you want to display the result.
A quick sample code, I haven’t tested it:
using UnityEngine;
using UnityEngine.UI;
using System;
public class InputFieldOperations : MonoBehaviour {
public InputField Field1;
public InputField Field2;
public Text Result;
public void Sum() {
int a = Convert.ToInt32(Field1.text);
int b = Convert.ToInt32(Field2.text);
int c = a+b;
Result.text = c.ToString();
}
public void Product() {
int a = Convert.ToInt32(Field1.text);
int b = Convert.ToInt32(Field2.text);
int c = a*b;
Result.text = c.ToString();
}
}
Set that as a component of something, drag and drop the inputfields and the text and set the OnClick callback of a button to call the Sum method, and the OnClick callback of another button to call the Product method.