首先我会解释现在发生了什么,然后是我期望发生的事情,最后是背后的代码
所以现在发生的事情是当我按下回车键时,文本的颜色变成了绿色
我期望发生的事情是文本的颜色变成红色
这基于我在字段中输入"Bad"的情况
//Please note I have edited uni9mportant code out
//Event Listener
inputField.onEndEdit.AddListener (delegate {
VerifyWords();
});
//Clss that handles the dictionary
public abstract class WordDictionary: MonoBehaviour{
public static Dictionary<string,bool> _wordDictionary = new Dictionary<string,bool> ();
private void Start(){
_wordDictionary.Add ("Bad",true);
}
}
//Function that handles the word verification
private void VerifyWords(){
if (openChat == false) { //If we done have open chat
bool hasBadWords = false; //Reset boolean
string[] stringSplit = inputField.text.Split (' '); //Split text string
for (int i = 0; i < stringSplit.Length; i++) { // Go through each word in the string array
if (WordDictionary._wordDictionary.ContainsKey (stringSplit[i])) { //If the word is in the dictionary
hasBadWords = true; //Then there is a bad word
}
}
if (hasBadWords == true) { //If a bad word was found
inputField.textComponent.color = Color.red; //Then the text should be red
} else {
inputField.textComponent.color = Color.green; //The text should be green
}
}
}
编辑 我加入了注释以表达我的思路
MonoBehaviour
派生脚本,则在Unity中会自动调用Start
函数。 - Programmer!
,比如说“如果字典中不包含这个键”,那么文本总是会变成红色……真的让我感到困惑,为什么会出现这种情况,我觉得代码看起来没问题。 - FlamingGeniusWordDictionary
中移除abstract
吗?我在想Unity无法调用Start
,因为它无法实例化一个抽象类。 - Ron Beyer