yyl
2025-05-16 f4c97339a01fdd75d8b862be572eefe66bd51d5a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
namespace vnxbqy.UI
{
    [RequireComponent(typeof(InputField))]
    public class InputSpecialWordLimit : MonoBehaviour
    {
        [SerializeField, Header("是否限制空格")] bool m_SpaceLimit = false;
        private void Awake()
        {
            var _input = GetComponent<InputField>();
            _input.onValidateInput = OnValidateInput;
        }
 
        private char OnValidateInput(string text, int charIndex, char addedChar)
        {
            if (char.GetUnicodeCategory(addedChar) == UnicodeCategory.Surrogate
                || char.GetUnicodeCategory(addedChar) == UnicodeCategory.OtherSymbol
                || char.GetUnicodeCategory(addedChar) == UnicodeCategory.OtherNumber
                || char.GetUnicodeCategory(addedChar) == UnicodeCategory.MathSymbol
                || char.GetUnicodeCategory(addedChar) == UnicodeCategory.OtherNotAssigned
                || addedChar == '\n')
            {
                return (char)0;
            }
            if (m_SpaceLimit)
            {
                if (addedChar == ' '
                 || addedChar == ' '
                 || char.GetUnicodeCategory(addedChar) == UnicodeCategory.SpaceSeparator)
                {
                    return (char)0;
                }
            }
            return addedChar;
        }
    }
}