11// Copyright (c) Microsoft Corporation. All rights reserved.
22// Licensed under the MIT License. See LICENSE in the project root for license information.
33
4+ using System ;
45using System . Collections . Generic ;
5- using System . Linq ;
66using UnityEngine ;
77using UnityEngine . Events ;
88using UnityEngine . Windows . Speech ;
@@ -44,23 +44,36 @@ public enum RecognizerStartBehavior { AutoStart, ManualStart };
4444 public KeywordAndResponse [ ] KeywordsAndResponses ;
4545
4646 private KeywordRecognizer keywordRecognizer ;
47- private Dictionary < string , UnityEvent > responses ;
47+ private readonly Dictionary < string , UnityEvent > responses = new Dictionary < string , UnityEvent > ( ) ;
4848
4949 void Start ( )
5050 {
51- if ( KeywordsAndResponses . Length > 0 )
51+ int keywordCount = KeywordsAndResponses . Length ;
52+ if ( keywordCount > 0 )
5253 {
53- // Convert the struct array into a dictionary, with the keywords and the keys and the methods as the values.
54- // This helps easily link the keyword recognized to the UnityEvent to be invoked.
55- responses = KeywordsAndResponses . ToDictionary ( keywordAndResponse => keywordAndResponse . Keyword ,
56- keywordAndResponse => keywordAndResponse . Response ) ;
57-
58- keywordRecognizer = new KeywordRecognizer ( responses . Keys . ToArray ( ) ) ;
59- keywordRecognizer . OnPhraseRecognized += KeywordRecognizer_OnPhraseRecognized ;
60-
61- if ( RecognizerStart == RecognizerStartBehavior . AutoStart )
54+ try
6255 {
63- keywordRecognizer . Start ( ) ;
56+ string [ ] keywords = new string [ keywordCount ] ;
57+ // Convert the struct array into a dictionary, with the keywords and the keys and the methods as the values.
58+ // This helps easily link the keyword recognized to the UnityEvent to be invoked.
59+ for ( int index = 0 ; index < keywordCount ; index ++ )
60+ {
61+ KeywordAndResponse keywordAndResponse = KeywordsAndResponses [ index ] ;
62+ responses [ keywordAndResponse . Keyword ] = keywordAndResponse . Response ;
63+ keywords [ index ] = keywordAndResponse . Keyword ;
64+ }
65+
66+ keywordRecognizer = new KeywordRecognizer ( keywords ) ;
67+ keywordRecognizer . OnPhraseRecognized += KeywordRecognizer_OnPhraseRecognized ;
68+
69+ if ( RecognizerStart == RecognizerStartBehavior . AutoStart )
70+ {
71+ keywordRecognizer . Start ( ) ;
72+ }
73+ }
74+ catch ( ArgumentException )
75+ {
76+ Debug . LogError ( "Duplicate keywords specified in the Inspector on " + gameObject . name + "." ) ;
6477 }
6578 }
6679 else
@@ -71,7 +84,7 @@ void Start()
7184
7285 void Update ( )
7386 {
74- if ( keywordRecognizer . IsRunning )
87+ if ( keywordRecognizer != null && keywordRecognizer . IsRunning )
7588 {
7689 ProcessKeyBindings ( ) ;
7790 }
0 commit comments