Home > front end >  How to set text in InputField in UnityEngine by code
How to set text in InputField in UnityEngine by code

Time:10-24

My problem is that after my changes in code, Unity doesn't do any actions with InputField (after starting the game, I mean). I want that after setting text value for InputField, this one changes in Unity after starting. Could you help me with it?
Code looks like:

public class TextBehaviourScript : MonoBehaviour
{ 
    public InputField input;
    void Start()
    {
        input.text = "some text for input";
       
    }
 }

I tried to do this by Awake() and GameObject as well, but It was unsuccessfully (maybe It was just my mistake)
Thank you in advance

CodePudding user response:

I used your script (added an include) and it works with a proper setup in Unity.

  1. Create Legacy Input Field (GameObject -> UI -> Legacy -> Input Field):

enter image description here

  1. Then add your script and drag the Input Field Component to the public field. Hit play and the input text changes. as expected:

enter image description here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChangeInputFieldText : MonoBehaviour
{
    public InputField input;
    void Start()
    {
        input.text = "some text for input";
    }
}

New Input field (TextMeshPro):

  1. Add Gameobject -> UI -> Input Field - TextMeshPro (import TMP Essentials if prompted!)

enter image description here

  1. Add your Script and drag the TMP Input Field in the slot. This time, your script needs a variable of type TMP_InputField and the required Import is using TMPro; See below:

code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class ChangeInputFieldText : MonoBehaviour
{
    public TMP_InputField input;
    void Start()
    {
        input.text = "some text for input";
    }
}
  • Related