|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- using System;
- using UnityEngine;
-
- namespace GamecraftModdingAPI.Interface.IMGUI
- {
- /// <summary>
- /// A text input field.
- /// This wraps Unity's IMGUI TextField and TextArea.
- /// </summary>
- public class Text : UIElement
- {
- private bool automaticLayout;
-
- /// <summary>
- /// Whether the text input field is multiline (true -> TextArea) or not (false -> TextField).
- /// </summary>
- public bool Multiline { get; set; }
-
- private string text;
-
- /// <summary>
- /// The rectangular area that the text field can use.
- /// </summary>
- public Rect Box { get; set; } = Rect.zero;
-
- /// <summary>
- /// An event that fires whenever the text input is edited.
- /// </summary>
- public event EventHandler<string> OnEdit;
-
- public void OnGUI()
- {
- string editedText = null;
- if (automaticLayout)
- {
- if (Multiline)
- {
- editedText = GUILayout.TextArea(text, Constants.Default.textArea);
- }
- else
- {
- editedText = GUILayout.TextField(text, Constants.Default.textField);
- }
- }
- else
- {
- if (Multiline)
- {
- editedText = GUI.TextArea(Box, text, Constants.Default.textArea);
- }
- else
- {
- editedText = GUI.TextField(Box, text, Constants.Default.textField);
- }
- }
-
- if (editedText != null && editedText != text)
- {
- OnEdit?.Invoke(this, editedText);
- text = editedText;
- }
- }
-
- /// <summary>
- /// The text field's unique name.
- /// </summary>
- public string Name { get; }
-
- /// <summary>
- /// Whether to display the text field.
- /// </summary>
- public bool Enabled { set; get; } = true;
-
- /// <summary>
- /// Initialize the text input field with automatic layout.
- /// </summary>
- /// <param name="initialText">Initial text in the input field.</param>
- /// <param name="name">The text field's name.</param>
- /// <param name="multiline">Allow multiple lines?</param>
- public Text(string initialText = null, string name = null, bool multiline = false)
- {
- this.Multiline = multiline;
- automaticLayout = true;
- text = initialText ?? "";
- if (name == null)
- {
- this.Name = typeof(Text).FullName + "::" + text;
- }
- else
- {
- this.Name = name;
- }
- IMGUIManager.AddElement(this);
- }
-
- /// <summary>
- /// Initialize the text input field.
- /// </summary>
- /// <param name="box">Rectangular area for the text field.</param>
- /// <param name="initialText">Initial text in the input field.</param>
- /// <param name="name">The text field's name.</param>
- /// <param name="multiline">Allow multiple lines?</param>
- public Text(Rect box, string initialText = null, string name = null, bool multiline = false) : this(initialText, name, multiline)
- {
- this.Box = box;
- automaticLayout = false;
- }
- }
- }
|