您的位置:首页 > 产品设计 > UI/UE

ngui UIInput输入汉字的那些坑

2017-08-29 20:46 183 查看
项目使用ngui,制作角色创建时,及聊天系统时,难免会输入中文字符。结果发现了很奇妙的情况,即限制的长度6(角色名长度)时,在editor中只能输入三个汉字,但是直接设置值可以显示6个汉字。查了下,发现UIInput中Insert处的代码如下处理:

//byte[] bytestr;
//fixed bug:中文和英文数字算作1个
//#if UNITY_STANDALONE_WIN
//        bytestr = System.Text.Encoding.GetEncoding("GB2312").GetBytes(mValue);
//#else
//           bytestr = System.Text.Encoding.Default.GetBytes(mValue);
//#endif
//        if (characterLimit > 0 && bytestr.Length > characterLimit)
//        {
//            //delete the final char
//            mValue = mValue.Substring(0, mValue.Length - 1);
//            while (System.Text.Encoding.Default.GetBytes(mValue).Length > characterLimit)
//            {
//                mValue = mValue.Substring(0, mValue.Length - 1);
//            }
//        }
当条件编译不为UNITY_STANDALONE_WIN(下同)时,即它本身的代码,用default的code(打印出来是gb2312),汉字是2个长度,从而只能输入三个汉字。于是,在Set函数处,如是处理
//            byte[] bytestr;
//            //fixed bug
//#if UNITY_STANDALONE_WIN
//            bytestr=System.Text.Encoding.GetEncoding("GB2312").GetBytes(mValue);
//#else
//           bytestr = System.Text.Encoding.Default.GetBytes(mValue);
//#endif
//            if (characterLimit > 0 && bytestr.Length > characterLimit)
//            {
//                //delete the final char
//                mValue = mValue.Substring(0, mValue.Length - 1);
//                while (System.Text.Encoding.Default.GetBytes(mValue).Length > characterLimit)
//                {
//                    mValue = mValue.Substring(0, mValue.Length - 1);
//                }
//            }

UpdateLabel();
if (notify) ExecuteOnChange();
从而,可使得设置的character limit在汉字时是统一的。但是,参考农药的聊天,会发现1个英文数字的长度和1个汉字是相同的。这样想想都有毛病。此外,用Encoding.Default判断长度,会导致打包成pc版本后,Default编码为UTf-8,此时1个汉字的长度是3.对比后,假设最大长度为6,则editor中允许输入3个汉字,打包成win版本呢,是2个汉字。简直是有病啊!于是,仔细思考后,将Insert处和Set处的代码注释掉。此时,1个中文和1个英文数字的长度就是一致了。此处对作者Insert处的代码,蜜汁问号。
然而,仍然有喜闻乐见的问题,即,输入时,插入后输入汉字,会使得从插入位置到结尾都选中,查了半天才找到原因。且修改方法如下(pc版本):

// Append IME composition
if (mLastIME != ime)
{
#if !UNITY_STANDALONE
mSelectionEnd = string.IsNullOrEmpty(ime) ? mSelectionStart : mValue.Length + ime.Length;
//当输入了中文,input.compositionString有值后,会导致end为字串的结尾...蜜汁问号...
#endif
mLastIME = ime;
UpdateLabel();
ExecuteOnChange();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Unity3d ngui