简体   繁体   中英

Setup Multi InputField in Unity 5

Currently, I have my code working correctly with one InputField (pressure) but I now trying to setup a second InputField to display the drillpipe input. How do I add another inputfield (ex. drillpipe) to my current script?

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

You'd indeed have problem with finding out more than one Component of same type with GetComponent<T> . I would recommend creating GameObject per InputField , put it as a child of GameObject holding your UserInput .

Then you'd just need to create two public fields that correspond to your InputField s, ie:

public InputField field1;
public InputField field2;

//Do something with them
void Start()
{
    DoStuff(field1);
    DoStuff(field2);
}

and assign them from inspector. Just drag GameObject holding each InputField and drop it on variable inside inspector. That way you'd know exactly which InputField you're using. You can also make a prefab from it for reusability and instantiation from code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM