Matt O'Connell Matt O'Connell - 3 months ago 8
C# Question

Input Value Converted To String

Recently I've been creating a game, and I've been creating a Menu.
At the beginning the player opens the Menu and enters a name into a UI Text Field, which I will convert to a string, so the player may be called that name throughout the storyline.

I've come across another Script on this website:

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

public class GUIFieldTest : MonoBehaviour {

public GameObject playerName;

public void Start ()
{
var input = gameObject.GetComponent<InputField>();
var se = new InputField.SubmitEvent();
se.AddListener(SubmitName);
input.onEndEdit.AddListener(SubmitName);

//or simply use the line below,
//input.onEndEdit = se; // This also works
}

private void SubmitName(string arg0)
{
Debug.Log(arg0);
}
}


I have tweaked this code so I can include a prefab of the Text Field as a GameObject, however I have recieved an error saying:


NullReferenceException: Object reference not set to an instance of an
object GUIFieldTest.Start () (at Assets/Scripts/GUIFieldTest.cs:13)


I understand that this error means that there is nothing assigned, and I understand how to fix the NullReferenceException. I am able to run the game, however the game freezes and the text field is not clickable. You cannot enter any text.

I know this is a very simple question, but it would be great for an explanation.

Answer

var input = gameObject.GetComponent<InputField>() should be

var input = playerName.GetComponent<InputField>().

When you use gameObject.GetComponent, it will only find components on the GameObject the script is attached to.

I assume that your InputField GameOBject is the playerName variable.

If this is not true the do var input = GameObject.Find("YourInputFieldGameOBject").GetComponent<InputField>().

Comments