【Unity】敏感词过滤

下方链接是一个需要过滤的敏感词汇的txt文件,可根据需要自行编辑。

https://files.cnblogs.com/files/weigangblog/SensitiveWords1.zip

这里是将txt文件放在StreamingAssets文件夹中,FilterHelp在启动之后加载使用,使用的时候传入字符内容直接返回过滤结果:

var result = FilterHelp.Instance.FilterWord(content);

下面为FilterHelper类代码:

using UnityEngine;
using System.Collections;
public class FilterHelp : MonoBehaviour
{
    private static string[] SentiWords = null; //定义一个接受文件内容的字符串数组
    public static FilterHelp Instance { get; private set; }
    /// <summary>
    /// 使用一个协程来进行文件读取
    /// </summary>
    /// <returns></returns>
    private IEnumerator LoadWWW()
    {
        WWW www;
        //不同平台下StreamingAssets的路径是不同的,这里需要注意一下。
        if (Application.platform == RuntimePlatform.Android)
        {

            www = new WWW(Application.streamingAssetsPath + "/" + "SensitiveWords1.txt");
        }
        else
        {
            www = new WWW("file://" + Application.streamingAssetsPath + "/" + "SensitiveWords1.txt");
        }

        yield return www;

        if (!(www.Equals("") || www.Equals(null)))
        {
            //Debug.Log(www.text);
            //将读取到的字符串进行分割后存储到定义好的数组中
            SentiWords = www.text.Split(',');
        }
    }

    private void Awake()
    {
        Instance = this;
    }

    //在Start()函数中开启协程加载文件
    private void Start()
    {
        StartCoroutine("LoadWWW");
        //添加输入事件监听
        //transform.GetComponent<InputField>().onValueChanged.AddListener(OnValueChanged);
    }

    /// <summary>
    /// 监听方法,该方法会在监测到输入值改变时被触发
    /// </summary>
    /// <param name="t"></param> 参数为当前输入的值
    public bool OnValueChanged(string t)
    {
        if (SentiWords == null)
            return false;
        print("..........");
        foreach (string ssr in SentiWords)
        {
            if (t.Contains(ssr))
            {
                if (!ssr.Equals(""))
                {
                    Debug.Log("包含敏感词汇:" + ssr + ",需要进行替换");
                    return true;
                    //将敏感词替换*
                    //string stt = transform.GetComponent<InputField>().text;
                    //int length = ssr.ToCharArray().Length;
                    //string s = "";
                    //for (int i = 0; i < length; i++)
                    //    s += "*";
                    //Debug.Log(stt.Replace(ssr, s));
                    //stt = stt.Replace(ssr, s);
                    //transform.GetComponent<InputField>().text = stt;
                }
            }

        }

        return false;
    }
}

 

posted @ 2020-04-19 10:59  weigang  阅读(908)  评论(0)    收藏  举报