unity3d - 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;
}
}
解决方案
正如错误所说,您试图将方法用作布尔值。你不能那样做。此外,您的方法逻辑ControlGUI
很奇怪-这些Up
和Down
应该来自哪里?
我认为您需要将参数传递给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
}
推荐阅读
- django - Django 使用 Postgres 在 JSONField 中注释计数
- git - error: failed to push some refs to 'https://git.heroku.com/nameless-cliffs-57613.git'
- javascript - 对于异步测试和钩子,确保调用了“done()”;如果返回一个 Promise,确保它解析 puppeteer 和 mocha
- ansible - Ansible Vault:加密以“-”开头的密码
- javascript - 税收和 Javascript 舍入问题
- php - WDSL 连接超时 (1006)
- azure - Azure SSIS IR - 使用 IR 节点临时文件夹中的文件
- javascript - 用户输入日期时如何显示日期?
- django - Django rest中的通用关系
- ckeditor - 如何使用 ckeditor 4 存储原始 html