首页 > 解决方案 > Unity语音识别器,如何与if语句结合使用

问题描述

我正在创建一个语音控制游戏。我正在创建的一个游戏是“射击目标”大炮游戏,当说出“射击”这个词时会发射一个炮弹。

我正在尝试将 Unity 的语音识别器与 if 语句结合使用,以便用我的声音移动 Slider UI 的填充区域。

但是,我的初始方法出现了一些错误,例如“无法将方法组 'Up' 转换为非委托类型bool。您是否打算调用该方法?”

PS这是我第一次使用StackOverflow,请多多关照。

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Windows.Speech; 
using UnityEngine;
using UnityEngine.UI; 

public class SliderControls : MonoBehaviour
{
    //Voice Controls Setup 
    private KeywordRecognizer keywordRecognizer;
    private Dictionary<string, Action> actions = new Dictionary<string, Action>();
    float sliderValue; 

    // Start is called before the first frame update
    void Start()
    {
        actions.Add("Up", Up);
        actions.Add("Down", Down);

        keywordRecognizer = new KeywordRecognizer(actions.Keys.ToArray());
        keywordRecognizer.OnPhraseRecognized += Recognization;
        keywordRecognizer.Start();   
    }

   private void Recognization(PhraseRecognizedEventArgs speech)
   {
        Debug.Log(speech.text);
        actions[speech.text].Invoke(); 
   }

   private void Up()
    {
        ControlGUI(); 
    }

    private void Down()
    {
        ControlGUI(); 
    }

    public void ControlGUI ()
    {
        if (Up)
        {
            sliderValue = sliderValue + 0.1F; 
        }
        else if(Down)
        {
            sliderValue = sliderValue - 0.1F; 
        }

        sliderValue = GUI.HorizontalSlider(new Rect(25F, 25F, 600F, 30F), sliderValue, 0.0F, 10.0F);
        return;
    }


}

标签: unity3dif-statementspeech-recognition

解决方案


正如错误所说,您试图将方法用作布尔值。你不能那样做。此外,您的方法逻辑ControlGUI很奇怪-这些UpDown应该来自哪里?

我认为您需要将参数传递给ControlGUI方法,因此您的代码将如下所示:

private void Up()
{
    ControlGUI("Up"); 
}

private void Down()
{
    ControlGUI("Down"); 
}

// You can also define enum Direction { Up, Down } or use int or any other approach
public void ControlGUI (string direction)
{
    if (direction == "Up")
    {
        sliderValue = sliderValue + 0.1F; 
    }
    else if(direction == "Down")
    {
        sliderValue = sliderValue - 0.1F; 
    }

    sliderValue = GUI.HorizontalSlider(new Rect(25F, 25F, 600F, 30F), sliderValue, 0.0F, 10.0F);
    return; // this return statement is redundant
}

推荐阅读