How do i set int value of inputfield with Content Type set to Integer in Unity? - unity3d

I am working with Unity 2018.
I have inputfield and 2 buttons.
When i click a button the expected behaviour is for the counter inside the field to change accordingly. For example:
{
int current_value = int.Parse(this.craftOrderInput.text);
if(current_value>0)
this.craftOrderInput.text = (current_value - 1) + "";
}
But this obviously fails because the (current_value - 1) + ""; is a string, but input field expects an integer. Setting an integer like so this.craftOrder.text = (current_value - 1) ; obviously cannot compile because text component expects a string.
I wanted to try Unity forums first but i cannot ask questions there because my style of writing reminds them of spam.
tldr; How do i set int value of inputfield with Content Type set to Integer?

The content type only affects which characters the user is allowed to type in the inputfield. Even when the content type is set to integer, changing the input field is still done by changing the text as a string. I made a little demo to test this and the following script worked for me.
using UnityEngine;
using UnityEngine.UI;
public class MakeSmaller : MonoBehaviour {
InputField inputField;
private void Awake()
{
inputField = GetComponent<InputField>();
}
public void Subtract()
{
int orig = int.Parse(inputField.text);
inputField.text = (orig - 1).ToString();
}
}

Related

{TextMeshPro problem} Coin collecting system that increases coin counter when the player is in contact with the sphere - works with Debug.Log. [Unity]

I made a coin collecting system that increases the number on a counter when the player comes in contact with the "coin" > sphere. I used Debug.Log to make sure that the counter works. It does. However, When I use TextMeshPro to display that value, it is stuck at zero.
public float moneyStart;
public float unit;
public float moneyNow;
public float displayedMoney;
private TextMeshPro textsss;
void Start()
{
TextMeshPro textsss = GetComponent<TextMeshPro>();
}
void OnCollisionEnter(Collision C_Info)
{
if (C_Info.collider.tag == "Currency")
{
displayedMoney = moneyNow + unit;
textsss.text = displayedMoney.ToString("0");
}
}
Visual for the counter stuck at zero
The script is in the TextMeshPro Element
Am I using TextMeshPro correctly?
How can I use it better?
Are there any errors?
How do I fix it?
Don't pass any argument to the .ToString() method
textsss.text = displayedMoney.ToString();
And to answer your questions, you are using TextMeshPro correctly, updating the text every time the field displayedMoney is getting updated

How to make UnityEngine.Event.numeric be true?

I am working on a simple tool that needs to check if a numeric key has been pressed using OnGUI in a MonoBehaviour. I tried every keys of my keyboard (even num pad and classical numerci keys) and none of them seems to set the property Event.numeric to true.
I am wondering what key will trigger the value change of that property.
Here is my sample code (Unity 2020.3.20 LTS)
private void OnGUI()
{
var evt = Event.current;
if (evt.type != EventType.KeyDown) return;
if (!evt.numeric) return;
Debug.Log("Foo");
}

Custom value slider unity

I want to return displayed value (a,b,c,d) not numbers (0.01-0.019 ect)
A help will be nice and many people will be happy.
This code look like percentage display but I dont want percentage I want a text
Mathf.RoundToInt(value * 100) + "%"
Instead of making a whole new custom slider, utilize what Unity already provides then map the output to whatever format you desire. Sliders can be set to have a fixed number of outputs as well as be fixed to only whole numbers.
If you look at the slider component in the editor, the fields Min Value, Max Value, and Whole Numbers should be set. The most important is to set Whole Numbers to true and Max Value to the highest possible value - 1 of your new mapped set.
Next, when the value changes for your slider, you will want to set a callback delegate to your script to retrieve the value.
You can either add the callback in the editor using the UnityAction UI in the editor or you can programmatically add the callback by accessing the onValueChange listeners and adding a new listener. For the example, I will do everything in code to remove any sort of confusion.
All that is left is to map our retrieved values our slider outputs to some desired output. As your desired output seem to just be alphanumeric values, you can actually make the solution even easier by knowing that taking an integer value and adding the character 'a' to it will result in the corresponding alphanumeric value (where 0 is mapped to a and 25 to z).
[SerializeField] private Slider slider = null;
private void Start()
{
slider.onValueChanged.AddListener(delegate { SliderValueChangedCallback(); });
}
/// <summary>
/// Called when our slider value changes
/// </summary>
private void SliderValueChangedCallback()
{
// grab out numeric value of the slider - cast to int as the value should be a whole number
int numericSliderValue = (int)slider.value;
// now, plot our value to an alphanumeric one
char alphaNumericValue = (char)(numericSliderValue + 'a');
Debug.Log(alphaNumericValue);
}
Now this solution will only work if you want your outputted values to be alphanumeric values. If you want a more modular solution, here is one:
[SerializeField] private Slider slider = null;
[SerializeField] private Text currentValue = null;
[SerializeField] private List<string> yourValueList = new List<string> { "First Message", "Second Message", "Third Value", "4 for some reason", "the letter 6" };
private void Start()
{
slider.onValueChanged.AddListener(delegate { SliderValueChangedCallback(); });
// assuring that our slider is setup properly to map values
slider.minValue = 0;
slider.maxValue = yourValueList.Count - 1;
slider.wholeNumbers = true;
}
/// <summary>
/// Called when our slider value changes
/// </summary>
private void SliderValueChangedCallback()
{
// grab out numeric value of the slider - cast to int as the value should be a whole number
int numericSliderValue = (int)slider.value;
// debugging - do whatever you want with this value
currentValue.text = yourValueList[numericSliderValue];
}
Here is a gif of it in action:
Let me know if you have questions. I was unsure if you visually want to show these markers on the slider as well, but that can also be done using the normalized positions and a horizontal layout group.

Unity InputField box always in focus

I am trying to create a simple math game in unity where player enters the answer to a math problem. Essentially all the user can do is type in answer and then enter.
Currently, I have it that user can enter into the input field, after they enter, when the next problem appears, they have to physically click on input field box again to enter the answer.
Is there a way to make it so you can enter the input field continuously without having to re-click the input-field?
Edit Below:
i put in the code below. How do i grab the inputfield if i get error Cannot implicitly covert type inputfield to gameobject.
GameObject inputField;
void Start()
{
GameObject inputField = gameObject.GetComponent<InputField>();
inputField.Select();
inputField.ActivateInputField();
You can autofocus the InputField by calling ActivateInputField after loading a new "problem". Not sure but maybe you also need to Select it first
// Not sure if this is needed
theInputField.Select();
theInputField.ActivateInputField();
Alternatively you can also listen for submissions and do e.g.
private void Start ()
{
// Make your InputField accept multiple lines
// See https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.InputField.LineType.MultiLineNewline.html
theInputField.lineType = InputField.LineType.MultiLineNewline;
// Instead of waiting for submissions use the return key
theInputField.onValidateInput += MyValidate;
}
private char MyValidate(string currentText, int currentIndex, char addedCharToValidate)
{
// Checks if a new line is entered
if (addedCharToValidate == '\n')
{
// if so treat it as submission
// -> clear the input and evaluate
EvaluateInput(theInputField.text.Trim('\0'));
theInputField.text = "";
return '\0';
}
return addedCharToValidate;
}
So actually the User never leaves the InputField at all.

IntSlider callback function? Editor Scripting

I just got into Editor Scripting recently and I'm still getting a hold of all the basics. I wanted to know if the IntSlider (that we use to create a slider of integer values) has any methods or functions that can be used to get more functionality?
Something like the Slider class:
You have -maxValue, -minValue, -value, -onValueChanged (Callback executed when the value of the slider is changed)
These work during the "Play" mode.
I need to access this information while in the editor. Specifically: I need to access the onValueChanged (if it exists) of the IntSlider so I can assign a function for it to execute.
IntSlider Code:
totalRooms = EditorGUILayout.IntSlider(new GUIContent ("Total Rooms"), totalRooms, 0, 10);
Is there a way to achieve this for the inspector? Or something that can be created to solve this? If you can point me in the right direction, I'd be grateful.
I'm using Unity 5.3.1f
There is no such event in Unity at the moment. However this can be implemented easily like this:
Add a UnityEvent in your actual script.
public UnityEvent OnVariablesValueChanged;
Then in your editor script check if value is changed. (Note: I tried to write easily understandable code sample for this. you can change it accordingly)
[CustomEditor(typeof(MyScript))]
public class MyScriptEditor : Editor
{
public override void OnInspectorGUI()
{
MyScript myTarget = (MyScript)target;
int prevValue = myTarget.variable;
myTarget.variable = EditorGUI.IntSlider(new Rect(0,0,100, 20), prevValue, 1, 10);
int newValue = myTarget.variable;
if (prevValue != newValue)
{
Debug.Log("New value of variable is :" + myTarget.variable);
myTarget.OnVariablesValueChanged.Invoke();
}
base.OnInspectorGUI();
}
}
Then add listener to OnVariablesValueChanged event from inspector.
Hope this helps.