Unity Input Field 一段时间后锁定之前输入的字符

Unity Input Field Lock previously typed characters after a time

我一直在 Unity C# 中玩文字游戏,但在我想要实现的反作弊机制方面陷入停滞。

在输入字段中输入第一个字母后,我启动 运行 一个 2 秒计时器。 2 秒后,在玩家没有提交或输入另一个字母的情况下,输入字段应将先前输入的字母锁定在输入字段中的位置,之后输入的任何字母都应在其后输入。

这是我目前的代码:

currTime = 0;
hasInput = false;
lockedString = "";

void Update(){
    if(hasInput){
        currTime += Time.deltaTime * 1;
        if(currTime >= 2){
            //Stores current string value of input field
            lockedString = inputField.text;
        }
    }
}

void OnInputValueChange(){
    currTime = 0;
    hasInput = true;
    if(lockedString != ""){
    inputField.text = lockedString + inputField.text;
    }
}

现在,每当输入字段的值发生变化时,我都是 运行 OnInputValueChange()。一旦计时器达到 2 秒,我还设法存储到目前为止输入的字符串,但我不知道如何使输入字段 "locks" 将锁定的字符串放在前面并允许更改字母在它后面打字。代码 inputField.text = lockedString + inputField.text; 只是在每次更改值时将 lockedString 变量添加到输入字段。

所需的结果在伪代码中是这样的:

//User types "bu"
//2 second timer starts
//During these 2 seconds, user can delete "bu" or continue typing
//User deletes "bu" and types "ah"
//Once the 2 second timer ends, whatever string is now in input is locked
//"ah" is now locked at the front of the input field
//After locking "ah", user cannot delete it anymore, but can continue typing

任何关于我如何实现类似目标的见解都将非常有帮助。感谢您抽出时间提供帮助,非常感谢!

目前,您只是简单地连接字符串。您将要检查字符串是否以相同的字符开头,如果不是,则完全覆盖输入:

void Update() {
    if (hasInput && ((Time.time - inputTime) > 2f))
    {
        //Stores current string value of input field
        lockedString = inputField.text;
        hasInput = false;
    }
}

void OnInputValueChange() {
    inputTime = Time.time;
    hasInput = true;
    if ((lockedString.Length > 0) && (inputField.text.IndexOf(lockedString) != 0)) {
        // Replace invalid string
        inputField.text = lockedString;
        // Update cursor position
        inputField.MoveTextEnd(false);
    }
}

注意:我已经实现了另一种测量时间的方法。随意用您自己的方法替换它。