【问题标题】:Unity: How do you create a fully working InputField in C#?Unity:如何在 C# 中创建一个完全正常工作的 InputField?
【发布时间】:2015-09-10 10:27:00
【问题描述】:

我正在尝试通过 C# 中的脚本创建一个 "UnityEngine.UI.InputField"。由于 Unity API 文档在代码示例方面非常缺乏,因此就像锁在你脚上的石头一样有用,我试图从编辑器中添加的 InputField 重新创建它。

我有

  • 创建了 InputField,
  • 为背景添加了一个图片组件,
  • 用于实际输入文本的 Text 组件和
  • 占位符的文本
  • 我还在我的场景中添加了一个 EventSystem

看起来一切正常,但输入不起作用。单击该字段似乎没有任何作用。

还需要做什么才能使其正常工作以使文本输入正常工作?

编辑:忘了说:手动放置的 InputField 在运行时会获得一个 InputField Input Caret 子对象。但是我的 C# InputField 不会自动得到这个。这个怎么加?

GameObject container = new GameObject();
container.name = "InputField";
container.transform.parent = _console.transform;
container.AddComponent<CanvasRenderer>();

_image = container.AddComponent<Image>();
_image.color = Utils.HexToColor32("0000000A");

GameObject textContainer = new GameObject();
textContainer.name = "Text";
textContainer.transform.parent = container.transform;
_text = textContainer.AddComponent<Text>();
_text.supportRichText = false;
_text.color = _console.colorText;
_text.font = _console.fontFace;
_text.fontSize = _console.fontSize;
_text.horizontalOverflow = HorizontalWrapMode.Overflow;

GameObject placeholderContainer = new GameObject();
placeholderContainer.name = "Placeholder";
placeholderContainer.transform.parent = container.transform;
_placeholder = placeholderContainer.AddComponent<Text>();
_placeholder.color = new Color(_console.colorText.r, _console.colorText.g, _console.colorText.b, _console.colorText.a / 2);
_placeholder.font = _console.fontFace;
_placeholder.fontSize = _console.fontSize;
_placeholder.fontStyle = FontStyle.Italic;
_placeholder.supportRichText = false;
_placeholder.horizontalOverflow = HorizontalWrapMode.Overflow;
_placeholder.text = "Enter command ...";

_inputField = container.AddComponent<InputField>();
_inputField.targetGraphic = _image;
_inputField.textComponent = _text;
_inputField.placeholder = _placeholder;

【问题讨论】:

  • 能否请您提供一份您的代码副本,以便我们看到您在说什么?
  • 我已经添加了相关的代码块。
  • @Rohit 为什么要删除我的源代码?
  • 我没有删除它,我只是签入了旧副本,它不存在。也许这是一个时间问题,我在添加源代码之前编辑的副本在您保存源代码时被保存。请重新添加。
  • 现在看来这是一个不错的问题,我已经投了赞成票。

标签: c# user-interface unity3d


【解决方案1】:

想通了。运行它的画布需要一个 GraphicsRaycaster 组件。

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    相关资源
    最近更新 更多