- Home /
How to print something if a user types in a specific word in the inputfield?
Hey guys, Basically I don't how to state this but here it goes. In the input field how to recognize a list of commands so when the user types in a command it print a sentences e.g. I type in "New Game" and it print something or switch to a new game scene
Sorry if this don't make sense
Answer by Hellium · Jan 27, 2017 at 08:39 AM
Here is a simple script I made. Let me know if you don't understand everything. I am comparing strings, but I think that regular expressions would be better. Especially if you want to play with command arguments.
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class CommandPrompt : MonoBehaviour
{
// Drag & Drop the inputfield in the inspector
public InputField inputfield;
private Dictionary<string, System.Action<string,string>> commands;
protected void Awake()
{
commands = new Dictionary<string, System.Action<string,string>>();
// Add the commands you want to recognise along with the functions to call
commands.Add( "new game", OnNewGameTyped );
commands.Add( "hello", OnHelloTyped );
// Listen when the inputfield is validated
inputfield.onEndEdit.AddListener( OnEndEdit );
}
private void OnEndEdit( string input )
{
// Only consider onEndEdit if the Submit button has been pressed
if ( !Input.GetButtonDown( "Submit" ) )
return;
bool commandFound = false;
// Find the command
foreach ( var item in commands )
{
if ( item.Key.ToLower().StartsWith( input.ToLower() ) )
{
commandFound = true;
item.Value( item.Key, input );
break;
}
}
// Do something if the command has not been found
if ( !commandFound )
Debug.Log( "No command found" );
// Clear the input field (if you want)
inputfield.text = "";
}
private void OnNewGameTyped( string command, string input )
{
Debug.Log( "Starting new game" );
UnityEngine.SceneManagement.SceneManager.LoadScene( 1 );
}
private void OnHelloTyped( string command, string input )
{
Debug.Log( "Hello my friend !" );
}
}
Thanks for the fast reply mate, I am going to try and figure out how you did it, let you know if I don't understand somethings. Thanks again for helping me
Is it possible if I don't have a enter button and only run if the enter key is pressed?
That's the purpose of the following line :
if ( !Input.GetButtonDown( "Submit" ) )
By default, in the Input manager, Submit is associated to the Enter key, but you could do something like :
if( !Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Return))
Thank you for you help. one last question do you usually reward people who answer you question good?
Your answer
