Transferring text of an input field to another input field on Unity - c#

Im working on this Unity AR project and im trying to add a function where I can transfer text of an input field to another input field.
I have tried various scripts and have tried it on the app but the text of input field still cannot be transferred to another input field.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RemarksTransfer : MonoBehaviour
{
public string theRemarks;
public GameObject inputField;
public GameObject textDisplay;
public GameObject secondInput;
public void StoreRemarks()
{
theRemarks = inputField.GetComponent<Text>().text;
textDisplay.GetComponent<Text>().text = theRemarks;
if (textDisplay.TryGetComponent<InputField>(out var secondInput))
{
secondInput.text = theRemarks;
}
}
}
This is the code that I have used. However, this is for transferring text from an input field to a text box instead of another input field. Therefore, displaying the text only but not being able to edit on it.
Long story short, Im just trying to transfer text from an input field to another input field and the text can be edited if the user wants to edit.

What you’re seeing here is a GameObject that has an InputField. For an InputField to work correctly, it has an associated Text component. Your code is looking for the Text component. Now, if your second object DOES have an InputField component, search for that, and use its text property to get and set the text. You should also bring doing the same thing for your original InputField as well. As the Unity documentation says, the visible text shown might be truncated, or have asterisks if it’s a password. That’s what you’d get, instead of the actual underlying text value.
So, assuming your textDisplay has an InputField component, you could use:
if ( textDisplay.TryGetComponent<InputField>( out var secondInput ) )
{
secondInput.text = theRemarks;
}

Related

how can i edit text in the UI within a script?

I wanted to edit the text in the UI to display a health value and score. but I don't know how I would go about creating code to edit the piece of text in the first place
To edit the Text component in Unity you need to do this:
Create a public Text field. In a function, for example Start (), it assigns a string to the Text component. Go to the inspector to assign the Text component to the public field.
using UnityEngine;
using UnityEngine.UI;
public class ChangeText : MonoBehaviour
{
public Text text;
void Start()
{
text.text = “example text”;
}
}
See the documentation here.
if you think my answer helped you, you can mark it as accepted. I would very much appreciate it :)

How to detect clicks on a dynamically updated TextMeshProUI text?

I'm trying to implement a functionality that can determine which word in the text the user clicked on. To do this, I use the TextMeshProUGUI element and the following code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro;
public class ExtraWordsDefinition : MonoBehaviour {
public TextMeshProUGUI text;
public string LastClickedWord;
void Start()
{
text = GetComponent<TextMeshProUGUI>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
var wordIndex = TMP_TextUtilities.FindIntersectingWord(text, Input.mousePosition, null);
if (wordIndex != -1)
{
LastClickedWord = text.textInfo.wordInfo[wordIndex].GetWord();
Debug.Log("Clicked on " + LastClickedWord);
}
}
}
}`
This code works fine if the text in the element is static (i.e.the text that I specified in the component's settings in the Unity inspector) then the words I click on are displayed in the console.
But, if I try to change the text of the component dynamically through the code, then the script stops detecting clicks on the text at all (the if condition does not work). Also, this way of changing text resets the text alignment settings.
At first I made code where the text was changed by assigning a new string to the ".text" property, but I also tried changing the text through the SetText() method, but that didn't change anything. Unfortunately, searching the internet didn't help me find an answer either.
Please help me figure out what is the reason.
First, I would add logs to verify that the mouse Vector and the TextMesh Vector are compatible. If that is the case, I would add a print when the test is updated and when the mouse is pressed to verify that the mouse pressing happens after the text has been updated and that the positions are still correct. I would also print the index to see if the text is actually found at the given position or if there is another problem. Also, ensure that nothing has a higher layer order than the text mesh after you change the text.

Problem with rich text and how it updates on the screen in unity

For my game, I wish to have a dialogue system where some words in the dialogue are colored differently. Right now, I have my normal white text being typed to the screen using the .ToCharArray command. This allows me to type one letter at a time to my screen. I've also looked and found something called Rich Text and Markup, which allows me to color my text with different colors while leaving the rest white. The issue is, the sentence is being typed and then updated in the ui to show the color, so for a brief second, are shown until the text changes green. Is there any way to make it so the text is typed with the color in effect? is there an asset that lets me change colors of certain words in unity? Any help would be appreciated!
Inside the DataBlock Scriptable object, ive typed the sentance i want into the text area. I then put and around the word I wanted to change. This caused the TypeSentance Coroutine to type out the sentance pulled from the scriptable object. This also made it so the TypeSentance Coroutine to print out the and around the text before updating a second later.
First Script
public class DataBlock : ScriptableObject
{
[Tooltip("Please Put Body Text In Here")]
[SerializeField] [TextArea(3, 10)] string bodyText;
public string getBodyText()
{
return bodyText;
}
}
Second Script
public class GameCode : MonoBehaviour
{
[SerializeField] DataBlock[] DataBlocks;
int currentDataBlock = 0;
private void update()
{
updateGraphic()
}
public void updateGraphic()
{
StopAllCoroutines();
StartCoroutine(TypeSentance(DataBlocks
[currentDataBlock].getBodyText()));
currentDataBlock++
}
IEnumerator TypeSentance(string sentance)
{
bodyTextBox.text = "";
foreach (char letter in sentance.ToCharArray())
{
bodyTextBox.text += letter;
yield return new WaitForSeconds(0.001f);
}
}
}
I expected the result to be that the text is outputted in the color of my choice, but instead it was printed with the and and then updated to show the color
Your description is not clear as you are missing some characters and don't give your example bodyText. Also it is not clear wich UI component you use.
Nevertheless I assume you are setting invalid tags as text as you iterate through your string. You find more about supported RichtText in Unity's documentation.
Example:
This text works fine:
"This text is <color=green>green</color> and <color=red>red</color>"
This text is missing a closing </color>-tag and wont be parsed as RichText by the UI.Text component:
"This text is <color=green>gree
To resolve this, you can parse the text (every time you extract a part) and check if you are missing a closing tag. If a tag is missing, you just add it at the end.
Also you have to ignore start-tags.
There are more things wrong with your code
Update must be written uppercase. Otherwise it is not called by Unity. But i guess are you calling it yourself from somewhere else? Than it is very misleading and should be renamed.
private void Update()
{
updateGraphic()
}
If you are updating correctly but a frame is showing the text full white, you only need to update the text while the object is off (gameObject.SetActive(false)) and then turn it off to apply the change on the very first frame gameObject.SetActive(true).

Growing InputField list in Unity

I need to implement input fields in unity which will be added on the fly as per the elements in a list. It should increase as per the objects present in a map "m_myClassMap".
Also, is it possible to fetch the position, layout settings ( i.e. x,y,z coordinates) of the existing Inputfields? I want these info to calculate the position of new inputfield.
For e.g.
List<InputField> inputFieldList = new List<InputField>();
foreach (MyClass myClassObj in m_myClassMap.Values)
{
// code below is just statement and is syntactically wrong
InputField newInputField = new InputField();
// Add properties like size or layout
// set the text
inputFieldList.Text = myClassObj.getInputBoxString();
inputFieldList.Add(newInputField );
}
I am not sure if its even possible..Any help will be welcome :)
Thanks!
The most robust thing to do here would be to use a layout group. This method plenty of well tested functionality.
Firstly add a a parent object. And add a Vertical Layout Group component to it. I've shown the hierarchy below by adding a Red panel to the blue panel. On the red panel is the Vertical Layout Group.
In this example I've used the inspector to manually add 4 input fields. Note the layout here is all automatic. I've included the settings on this particular input field below, you'll be able to experiment in the inspector and very quickly see what impact the various options have.
Now for your particular solution, you want to add the items programatically rather than through the inspector. For this you'll want to create a GameObject with a reference to the object holding the layout group.
Programatic Creation
The below code will add a list of prefabs to a class. (In this case the parent class should contain the Vertical Layout Group component)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LayoutGroupExample : MonoBehaviour {
public GameObject layoutObject;
public GameObject inputFieldPrefab;
void AddInputFields(){
var inputFieldList = new List<string>(){"First Name", "Last Name", "Email"};
foreach(var fieldName in inputFieldList){
GameObject go = GameObject.Instantiate(inputFieldPrefab);
go.name = fieldName;
go.transform.SetParent(layoutObject.transform);
var inputField = go.AddComponent<InputField>();
}
}
}
In the inspector assign the object containing the layout group to the layoutObject field.
Assign a prefab (which should be an Input Field object) to the inputFieldPrefab field)

Unity compare if two input fields have same value

How can I achieve this? A function can take only 1 argument in Unity for an event.
There are two different input fields in the same canvas which I'd like to compare.
I'm assuming this can be done using object as argument but I don't know which object I can pass. I tried dragging the canvas and input field gameObject(I'm guessing that's what it's called) to the object parameter field of my selected function but they don't get accepted.
This is where I want to attach the script:-
InputFields are not GameObject. They are objects of UI.InputField class. So in your script import UI with
#using UnityEngine.UI;
Then create 2 InputField object.
public InputField inp1;
public InputField inp2;
then drag your InputFields to them. then you can compare their text like that:
if( inp1.text == inp2.text) {}
Edit: You shouldnt attach a script to there, because the variables may change dynamically. attach this script I have wroten to an empty game object, add new snippet on below to script, and then attach this empty game object to event field that you showed. Then you should select the function will be called when edit ended. For this, create two different function in script for each input field as:
//Call this on EndEdit for inputField1
public void InpField1EndEdit()
{
//compare input fields here or make what you want
}
//Call this on EndEdit for inputField2
public void InpField2EndEdit()
{
//compare input fields here or make what you want
}

Categories

Resources