Skip to content

Instantly share code, notes, and snippets.

@nicetrysean
Created May 24, 2016 10:31
Show Gist options
  • Save nicetrysean/6b643addc84fd4171d5efa175ae7253c to your computer and use it in GitHub Desktop.
Save nicetrysean/6b643addc84fd4171d5efa175ae7253c to your computer and use it in GitHub Desktop.
Submit a string with a simple InputLabel and Button! (Unity 5.1+)
using System;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Events;
using UnityEngine.UI;
public class TextForm : MonoBehaviour
{
//Since we're using UnityEvent<T0> we need to implement the string type
public class TextEvent : UnityEvent<string> { }
public TextEvent TextSubmitted;
[SerializeField] //Display private variable in Inspector
private InputField _inputField;
[SerializeField]
private Button _submitButton;
private string _inputFieldValue;
void Start()
{
//http://blogs.unity3d.com/2015/08/25/the-unity-assertion-library/
Assert.IsNotNull(_inputField, "TextForm Requires InputField UI Component!");
Assert.IsNotNull(_submitButton, "TextForm Requires Button UI Component!");
//Listen to value changes, and events
_submitButton.onClick.AddListener(SubmitButton);
_inputField.onValueChanged.AddListener(InputFieldValueChanged);
}
/// <summary>
/// Updates cached value as the InputField changes
/// </summary>
/// <param name="value">InputField string</param>
void InputFieldValueChanged(string value)
{
_inputFieldValue = value;
}
/// <summary>
/// Calls the UnityEvent to fire with the value
/// </summary>
void SubmitButton()
{
TextSubmitted.Invoke(_inputFieldValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment