我目前正在尝试在Unity中设置多个输入字段并遇到问题。我只能输入一个输入(intPressure),但不知道如何添加第二个输入(钻杆)。在我看来,Unity一次只允许一个输入字段。我认为只需将其更改为InputField2,ect就能解决问题,但这似乎无法奏效。其他人提到创建一个空的游戏对象并将输入字段插入每个游戏对象。
老实说,我仍然对如何设置第二个输入字段感到困惑。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UserInput : MonoBehaviour {
InputField input;
int intPressure = 0;
int drillpipe = 0;
public DataManager data;
void Start ()
{
var input = gameObject.GetComponent<InputField>();
var se= new InputField.SubmitEvent();
se.AddListener(SubmitName);
input.onEndEdit = se;
}
private void SubmitName(string pressure)
{
var pressureScript =
GameObject.FindObjectOfType(typeof(DataManager)) as DataManager;
if (int.TryParse(pressure, out intPressure))
{
pressureScript.pressure = intPressure;
}
else
{
// Parse fail, show an error or something
}
}
}
答案 0 :(得分:2)
我不确定你想要实现它的方式(使用单个GameObject),但是你肯定能够做到这一点,如果你有几个GameObjects(每个控件一个对象)嵌套在另一个GameObject中(让& #39; s称之为UserInputRoot),如下所示:
UserInputRoot (has UserInputController script)
|
+--- InputPressure (has InputField component)
|
+--- InputDrillpipe (has InputField component)
控制脚本将有一些公共InputField或几个私有的,在Start()或Awake()方法中初始化:
class UserInputController : MonoBehaviour {
//These can be set from the inspector and controlled from within the script
public InputField PressureInput;
public InputField DrillpipeInput;
// It would be better to pass this reference through
// the inspector instead of searching for it every time
// an input changes
public DataManager dataManager;
private void Start() {
// There is no actual need in creating those SubmitEvent objects.
// You can attach event handlers to existing events without a problem.
PressureInput.onEndEdit.AddListener(SubmitPressureInput);
DrillpipeInput.onEndEdit.AddListener(SubmitDrillpipeInput);
}
private void SubmitDrillpipeInput(string input) {
int result;
if (int.TryParse(input, out result)) {
dataManager.drillpipe = result;
}
}
private void SubmitPressureInput(string input) {
int result;
if (int.TryParse(input, out result)) {
dataManager.pressure = result;
}
}
}
顺便说一句,代码的格式化绝对是残酷的。你必须解决它。
答案 1 :(得分:0)
看起来你正在显示的脚本附加到输入字段gameobject是正确的吗?您的对象中有一个名为input
的成员变量,但您在input
方法中创建了一个新变量Start
。不要将脚本附加到第一个InputField
,而是在编辑器中创建一个空的游戏对象并附加脚本。在脚本中添加两个公共成员:
public class UserInput : MonoBehaviour {
public InputField PressureInput;
public InputField DrillPipeInput;
现在回到编辑器,当你选择空的游戏对象时,你会看到两个输入字段出现。将两个输入字段拖放到每个输入字段的插槽中。现在,当场景开始时,您的UserInput脚本将使用输入字段进行设置,您可以同时使用它们。