【问题标题】:Unity string replacement统一字符串替换
【发布时间】:2020-09-04 14:18:31
【问题描述】:

我在使用统一引擎时遇到了一点问题。 我正在尝试结合一种方法来替换另一个字符串中的字符串。 如果我使用一个字符串,像往常一样设置,代码就可以工作(例如 string b = "whatever"); 但是当我尝试使用列表中的变量时,输出不会被修改(例如excludedWords [0])。 我试图在我的 excludeWords 变量的所有位置将它转换为字符串,但仍然没有成功。

有什么见解吗?

using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using TMPro;

public class FilterRex : MonoBehaviour
{
    List<string> excludedWords;
    [SerializeField]TextAsset excludedWordsFile;

    [SerializeField]TMP_InputField inputField;

    // Start is called before the first frame update
    void Start()
    {
        //this code accesses the words from the lists that need to be banned
        excludedWords = new List<string>();
        string[] lines = excludedWordsFile.text.Split('\n');
        foreach(string line in lines)
        {

            excludedWords.Add(line);
        }
        Debug.Log(excludedWords[0]);
        
    }
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Return))
        {
            PrepareTheWord();
        }
    }

    public void PrepareTheWord()
    {
            string innerWord = inputField.text.ToLower();
            string b = excludedWords[0].ToString());
            inputField.text = ReplaceTheWord(b, innerWord);
    }
    public string ReplaceTheWord(string _replace, string _from)
    {
        string output = _from.Replace(_replace, "");
        return output;
    }
}

【问题讨论】:

  • 而不是使用Input.GetKeyDown,我宁愿使用例如onValueChanged

标签: c# string unity3d filter replace


【解决方案1】:

如果你想改变列表中的字符串值,你需要直接赋值给它:

excludedWords[0] = ReplaceTheWord(excludedWords[0], innerWord);

C# 中的字符串是不可变的,所以如果你想改变它们的值,你必须重新赋值给它们。

编辑: 如果您想替换输入文本中出现的排除单词,您的 PrepareTheWord 方法可能如下所示:

public void PrepareTheWord()
{
    string innerWord = inputField.text.ToLower();

    foreach (string excludedWord in excludedWords)
    {
        innerWord = innerWord.Replace(excludedWord, "");
    }

    inputField.text = innerWord;
}

这不是最有效的方法,但它应该可以完成这项工作。

【讨论】:

  • 我已经测试了你的想法,我得到一个 ArgumentException: oldValue 是空字符串。同样,如果我直接写 ReplaceTheWord("theWordThatIWant", innerWorld);会工作的。
  • 除此之外,我不想更改excludedWords 中的字符串。它们仅作为检查的参考
  • 那我真的不知道你在问什么。你只想要b = ReplaceTheWord(b, innerWord); inputField.text = b;吗?
  • 我想检查excludedWords[0]。 inputField 有一个用户介绍的词。当我点击回车时,我正在运行这个功能。此函数获取输入。在 ReplaceTheWord 中,我正在检查一个列表。如果列表中有一个可以在 inputField 中找到的单词,那么我将其删除,只留下单词的其余部分。
  • 我刚刚注意到:string[] = {"word1", "word2"} 不等于我创建的列表:excludedWords[0] 和 excludeWords[1]。我现在正在考虑延期执行,但我不确定是不是这样
【解决方案2】:

所以为了快速修复。我注意到,如果我创建一个数组并输入该数组的元素,它将起作用。不是最有效的方式,也不是最令人愉快的方式,但它会暂时完成工作。

在另一个笔记上。我不确定这是否是统一的问题,但我确信这不是 PC 的问题。从 2019 年开始,我已经在三台具有不同统一版本的不同 PC 上测试了此代码。它们的行为似乎都相同。 我相信我会发现这个问题,但目前,我将专注于其他更新。 我要感谢所有阅读并回复我的询问的人,祝大家有个美好的一天!

我已经测试了 unity 2018 版本,仍然是同样的问题,是用一个新项目制作的。

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2013-12-03
    • 2020-01-12
    • 2017-01-28
    • 2017-03-07
    相关资源
    最近更新 更多