繁体   English   中英

如何限制输入长度的数字?

[英]How can I limit the numbers typing input length?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;

public class SecurityKeypadKeys : MonoBehaviour
{
    [SerializeField] private int _number;

    public event Action<int> onKeyPressed;

    private void Awake()
    {
        name = $"Key {_number}";
    }

    private void OnMouseDown()
    {
        onKeyPressed?.Invoke(_number);
    }
}

这个脚本获取按下的数字并将它们显示在文本 ui 中:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SecurityKeypadSystem : MonoBehaviour
{
    [Header("References")]
    // rather let this class control the display text
    [SerializeField] private TextMesh _text;

    [Header("Settings")]
    // also rather let this class control the length of a code
    [SerializeField] private int _codeLength = 8;

    [Header("Debugging")]
    [SerializeField] private GameObject[] _keyPadNumbers;
    [SerializeField] private List<int> _code = new List<int>();

    // This will be invoked once the code length has reached the target length
    public event Action<int> OnCodeComplete;

    // Start is called before the first frame update
    private void Start()
    {
        var KeyPadNumbersParent = GameObject.FindGameObjectWithTag("KeypadParent").GetComponentsInChildren<Transform>(true);
        foreach (Transform child in KeyPadNumbersParent)
        {
            if (child.gameObject.GetComponent<SecurityKeypadKeys>() != null)
            {
                var securityKeypadKeys = child.gameObject.GetComponent<SecurityKeypadKeys>();
                securityKeypadKeys.onKeyPressed -= HandleKeyPressed;
                securityKeypadKeys.onKeyPressed += HandleKeyPressed;
            }
        }
    }

    private void OnDestroy()
    {
        // just for completeness you should always remove callbacks as soon as they are not needed anymore
        // in order to avoid any exceptions
        foreach (var keyPadNumber in _keyPadNumbers)
        {
            var securityKeypadKeys = keyPadNumber.GetComponent<SecurityKeypadKeys>();
            securityKeypadKeys.onKeyPressed -= HandleKeyPressed;
        }
    }

    // this is called when a keypad key was pressed
    private void HandleKeyPressed(int value)
    {
        // add the value to the list
        _code.Add(value);

        if (_code.Count != _codeLength)
        {
            _text.text += value.ToString();
        }

        // Check if the code has reached the target length
        // if yes prcoess further
        if (_code.Count == _codeLength)
        {
            // if it reached the length combine all numbers into one int
            var exponent = _code.Count - 1;
            float finalCode = 0;
            foreach (var digit in _code)
            {
                finalCode += digit * Mathf.Pow(10, exponent);
                exponent--;
            }

            // invoke the callback event
            OnCodeComplete?.Invoke((int)finalCode);

            // and reset the code
            StartCoroutine(ResetCodeTime());
        }
    }

    IEnumerator ResetCodeTime()
    {
        yield return new WaitForSeconds(1f);

        ResetCode();
    }

    // Maybe you later want an option to clear the code field from the outside as well
    public void ResetCode()
    {
        _code.Clear();
        _text.text = "";
    }

    // also clear the input if this gets disabled
    private void OnDisable()
    {
        ResetCode();
    }
}

在这种情况下,代码长度为 8 :

private int _codeLength = 8;

在 HandleKeyPressed 中,我启动了一个协程,以在文本 ui 上显示最后输入的数字。

问题是如果玩家打字的速度不够快,但不够快,它会在协程重置之前显示更多的 3 位数字。 我试图通过添加检查来避免这种情况:

if (_code.Count != _codeLength)
            {
                _text.text += value.ToString();
            }

但它不起作用。 如果我输入足够快,它会在重置前在文本 ui 上显示更多 3-4 位数字。 我希望在任何情况下玩家都只能输入 8 位数字或代码的长度,如果它是 8、10 或 2,而不是更多。

您应该能够通过使用Range属性来解决此问题,如此处所述

直接从示例中,根据您的需要修改它:

    // This int will be shown as a slider in the Inspector
    [SerializeField]
    [Range(0, 99999999)]
    private int _number;

您可以使用 bool 来告诉您代码是否正在重置:

bool isResetting;
IEnumerator ResetCodeTime()
{
    isResetting = true;
    yield return new WaitForSeconds(1f);
    ResetCode();
    isResetting = false;
}

然后你可以在HandleKeyPressed检查它:

private void HandleKeyPressed(int value)
{
    if(isResetting){
        //cannot enter more digits, code is resetting. 
        return;
    }
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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