等待下一个输入并存储它(Unity / C#)

时间:2013-06-25 07:09:14

标签: c# input unity3d

我再说一次:D 我得到了下一个问题,但这次看起来我无法解决它,它也不应该是语法问题^^

好吧,现在我正在为我们的Classproject尝试为UNity3D(在C#中)创建一个输入类。我得到了输入本身,一切都很好。但我必须这样做的原因,使控件在运行时可更改,仍然是一个问题。我尝试了不同的方法来保存密钥(文本字段和编写密钥代码 - >我们的游戏设计师不喜欢它)。现在我尝试用Coroutines做这个,我的最后一次尝试是将它转移到另一个函数并在鼠标释放后启动所有代码并且不应该输入任何输入。无论如何,它缺乏工作。这是应该发挥魔力的守则:

    void PassKey(string wantedKey)
{
    if (Input.GetKey(KeyCode.Mouse0) == false)
    {
        Event uInput = Event.current;
        wantedKey = uInput.character.ToString();
        Debug.Log (wantedKey + uInput.character);
    }
}

在这里调用:

        if(GUI.Button(new Rect(0,0,qScreenWidthX / 2, qScreenHeightX / 5), rightText))
    {

        PassKey(right);
    }

(每个键都有此按钮。)

你们有没有想过如何在鼠标释放后等待下一个输入?

我不需要具体的代码,但可能暗示我如何才能使这个工作。

3 个答案:

答案 0 :(得分:0)

如果我的问题是真的,你需要跟踪鼠标释放后按下的下一个键,这不是很难解决,只需在任何鼠标释放后(在鼠标释放委托中)设置一个布尔值(x) true,对于其他事件委托(导致取消进程的任何事件)将值(x)设置为false,而不是在按键时你会识别鼠标是否在它之前发布,简单:

void mouseReleased(){// event when your mouse get released
   this.x=true;
}

void anyOtherEvent(){// for any other event that cancel the process, like wheel
   this.x=false;
}

void keyPressed(){//
   if(this.x){
     //ddo your operation
   }
   this.x=false;
}

希望我的问题是对的。

答案 1 :(得分:0)

根据OP上面的澄清评论,这里有一个片段,适用于简单的键,如'a','b','c'等。

捕获击键的最简单方法是在单击鼠标时使用简单标记进行存储,或者使用任何方法来指示要重新分配下一个键。在下面的示例中,单击鼠标左键时,代码将监视Input.inputString是否为空。当Input.inputString包含任何内容时,ReassignKey()将使用第一个键击作为您要使用的键分配。

请记住,如果帧之间存在较大的延迟,inputString可能包含多个keyStrokes。这就是为什么我只使用第一个角色。

public class KeyCapture : MonoBehaviour {
bool captureKey = false;
string assignedKey = "a";

// Update is called once per frame
void Update () {
    ReassignKey();

    // Mouse-click = wait for next key press
    if(Input.GetButtonDown("Fire1")){
        captureKey = true;
        Debug.Log("Waiting for next keystroke");
    }

    // Display message for currently assigned control.
    if(Input.GetKeyDown(assignedKey)){
        Debug.Log("Action mapped to key: " + assignedKey);
    }
}

void ReassignKey(){
    if(!captureKey)return;

    // ignore frames without keys
    if(Input.inputString.Length <= 0)return;

    // Input.inputString stores all keys pressed
    // since last frame but I only want to use a single
    // character.
    string originalKey = assignedKey;
    assignedKey = Input.inputString[0].ToString();
    captureKey = false;

    Debug.Log("Reassigned key '" + originalKey + "' to key '" + assignedKey + "'");
}
}

答案 2 :(得分:0)

你的@Jerdak和@user 2511414.我得到了问题的解决方案:D今天早上有点像顿悟,返回被击中的Key所需的代码是:

for(int i = 0; i < e; i++)
    {
        if(Input.GetKey((KeyCode)i))
        {
        return (KeyCode)i;
        }
            {

迭代KeyCodes并检查是否按下任何键,然后返回实际按下的键。 其他解决方案的问题在于我的Lead讨厌多个可避免的If-parts。