Unity开发之重写InputField

来源:互联网 发布:java 打印日志log 编辑:程序博客网 时间:2024/06/04 18:52

Unity UGUI提供的InputField组件可以让我们输入文字,但是他的输入字符种类限制只有那几种,对于我们有自己需求来说可能不能满足。这时候我们就需要进行对InputField类里的一些成员函数进行重写。我们打开InputField类,会发现两个看着跟输入字符有关系的函数:

       //        // 摘要:        //     ///        //     Append a character to the input field.        //     ///        //        // 参数:        //   input:        //     Character / string to append.        protected virtual void Append(char input);        //        // 摘要:        //     ///        //     Append a character to the input field.        //     ///        //        // 参数:        //   input:        //     Character / string to append.        protected virtual void Append(string input);
而我们需要检测每次输入的字符,所以我们打算选择第一个函数进行重写。假设我们的需求如下:设定InputField只能输入数字和“.”。对于中文、字母其他的输入都进行屏蔽。

首先,我们创建一个脚本,命名为MyInputField,然后让他继承于InputField类,我们在脚本里进行重写:代码如下:

public class MyInputField : InputField {    protected override void Append(char input)    {        //用正则表达式进行检测 当满足条件的字符可以被输入进去        if(System.Text.RegularExpressions.Regex.IsMatch(input.ToString(),@"[.]")|| Char.IsNumber(input))            base.Append(input);    }}


然后找到我们的InputField物体,将上面的InputField组件去掉,挂上我们的MyInputField脚本,就可以实现我们的需求了。记得挂载完我们的脚本后将Text Component以及Placeholder指定上。


原创粉丝点击