在 Unity3d 中设置多个输入字段时遇到问题

Having Issue with Setting Up multiple Input Field in Unity3d

我目前正在尝试在 Unity 中设置多个输入字段,但遇到了问题。我只能让一个输入工作(intPressure),但不知道如何添加第二个输入(钻杆)。在我看来,统一一次只允许一个输入字段。我认为只需将其更改为 InputField2 等就可以解决问题,但这似乎不起作用。其他人提到创建一个空的游戏对象并将输入字段插入每个游戏对象。

老实说,我对如何设置第二个输入字段仍然很困惑。

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
            }
        }
   }

您显示的脚本似乎附加到输入字段游戏对象,对吗?您的对象中有一个名为 input 的成员变量,但随后您在 Start 方法中创建了一个新变量 input。不要将脚本附加到您的第一个 InputField,而是在编辑器中创建一个空游戏对象并将脚本附加到它。在脚本中添加两个 public 成员:

 public class UserInput : MonoBehaviour {

  public InputField PressureInput;
  public InputField DrillPipeInput;

现在回到编辑器,当您 select 您的空游戏对象时,您应该会看到两个输入字段。将两个输入字段拖放到每个输入字段的插槽中。现在,当场景开始时,您的 UserInput 脚本将使用输入字段进行设置,您可以同时使用它们。

我不确定你想要实现这个的方式(使用单个游戏对象),但是如果你有几个游戏对象(每个控件一个对象)嵌套在另一个游戏对象中,你肯定能够做到这一点(我们称它为 UserInputRoot),如下所示:

  UserInputRoot (has UserInputController script)
  |
  +--- InputPressure (has InputField component)
  |
  +--- InputDrillpipe (has InputField component)

控制脚本将有几个 public 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;
        }
    }
}

顺便说一下,您的代码格式非常糟糕。你必须修复它。