在开发网络游戏的聊天功能模块时,需要对字符长度进行限制以免发送超长包,不过因为玩家输入了emoji后会导致长度无法正常处理,此时偷懒的办法就是限制emoji的输入
在UGUI的InputField进行输入时执行该方法:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Text.RegularExpressions;
public class InputRestrictionEmoji : MonoBehaviour {
InputField mtext;
private void Start()
{
mtext = GetComponent<InputField>();
if(mtext)
{
mtext.onValueChanged.AddListener(OnInputValue);
}
}
void OnInputValue(string value)
{
try
{
string msg = mtext.text;
//屏蔽emoji
string result = Regex.Replace(msg, @"p{Cs}", "");
mtext.text = result;
}
catch
{
Debug.Log("输入异常文字,出错");
mtext.text = "";
}
}
}
如果还是不放心可以try-catch一下,记得还要限制一下字符长度啊
特别感谢:
EmojiText https://github.com/zouchunyi/EmojiText
Unity-UI-emoji https://github.com/mcraiha/Unity-UI-emoji
twemoji https://github.com/twitter/twemoji