Unity UI InputField在OnEndEdit时检测输入或esc键

时间:2016-03-23 12:01:19

标签: unity3d input-field

我正试图弄清楚如何使用'enter'或'esc'键检测编辑InputField的结束。我有一个可行的解决方案,但是想知道是否有更好的方法(使用已经存在的Unity内容)。实际上使用Unity 4.7.1

以下是实际的解决方案:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class CustomInputField : InputField, ICancelHandler 
{
    // Action others can subsribe
    public System.Action<InputField, bool /*true: enter key, false: cancel key*/> OnCustomEndEdit = null;

    override public void OnPointerClick (PointerEventData eventData) {
        base.OnPointerClick( eventData );
        if( eventData.clickCount > 2 ) {
            SelectAll();
        }
    }


    // Need to presss 'enter' twice in order to receive this event. NOT USING IT!
    override public void OnSubmit(BaseEventData eventData) {
        base.OnSubmit( eventData );
    }

    // Need to presss 'esc' twice in order to receive this event. NOT USING IT!
    public void OnCancel(BaseEventData eventData) {
    }


    // This event happens before Unity calls the Update() funcion
    public void OnEndEdit( string value ) {
        if( Input.GetKeyDown( KeyCode.KeypadEnter ) || Input.GetKeyDown( KeyCode.Return ) ) {
            if( OnCustomEndEdit != null ) {
                OnCustomEndEdit( this, true );
            }
            Debug.Log( "Enter Key: " + this.text );
        }
        else {
            if( Input.GetKeyDown( KeyCode.Escape ) ) {
                if( OnCustomEndEdit != null ) {
                    OnCustomEndEdit( this, false );
                }
                Debug.Log( "Esc Key" );
            }
        }
    }        
}

0 个答案:

没有答案