簡體   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