Brendonn
Brendonn

Reputation: 1

Transferring text of an input field to another input field on Unity

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.

Upvotes: 0

Views: 330

Answers (1)

Milan Egon Votrubec
Milan Egon Votrubec

Reputation: 4049

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;
}

Upvotes: 1

Related Questions