Gameobject Movement on Text input in Unity3d

This is the on demand tutorail where i will simply show how to control object movement on text input. A user will provide text input in order to control an object movement. Lets get started:


  1. Create a demo scene with a cube and plane.
  2. Create an input field for user input
  3. Create a button 
  4. Create a Text Game object for showing error


Scripting
  1. Create a Script MovementOnText and attach it to your cube. Copy from below, the script is self-explanatory with comments:
  2. Go to you Cube object and Drag n Drop Cube to your on click event of the button and attached GetInputText Method to it and also Assign input filed into its parameter.
  3. Lets play and input commands like Move, Back, left, right, up, down


using UnityEngine;
using UnityEngine.UI;
public class MovementOnText : MonoBehaviour
{
/// <summary>
/// object movement speed
/// </summary>
public float speed = 2;
/// <summary>
/// store last user input into string
/// </summary>
private string lastInput;
/// <summary>
/// If the input not recognized then, show the error
/// </summary>
public Text errorText;
void Update()
{
if (lastInput == "move")
{
MoveForward(Vector3.forward);
}
else if (lastInput == "back")
{
MoveForward(-Vector3.forward);
}
else if (lastInput == "left")
{
MoveForward(Vector3.left);
}
else if (lastInput == "right")
{
MoveForward(Vector3.right);
}
else if (lastInput == "up")
{
MoveForward(Vector3.up);
}
else if (lastInput == "down")
{
MoveForward(Vector3.down);
}
else
{
errorText.enabled = true;
}
}
/// <summary>
/// Move object on specifc direction
/// </summary>
/// <param name="MovementVector">Movement vector</param>
void MoveForward(Vector3 MovementVector)
{
transform.Translate(MovementVector * speed * Time.deltaTime);
errorText.enabled = false;//movement text reconized thats why turn off the text
}
/// <summary>
/// Get Input Text, Attach it to your button
/// </summary>
/// <param name="input">input field where user will enter text</param>
public void GetInputText(InputField input)
{
lastInput = input.text.ToLower();
}
}

Post a Comment

0 Comments