I am trying to make a game where the player is controlled by an input field. When I try to store the value or the written text from the input field in a String and the compare the string to the solution string, it doesn't work. I have tried to work with debug.log functions everywhere to see when the code stops working, but I still can't see what the problem is. I have been looking for YouTube videos, unity-& other game development forums, but none of the proposed solutions seem to work with my code. I am fairly new to game development, and so maybe the solution is easy.
Here is the code i used but doesn't work as expected:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InputFieldComparision : MonoBehaviour
{
public InputField inputFieldInMainUi;
private string Txt;
void Update()
{
Txt = inputFieldInMainUi.text.ToUpper();
Debug.Log(Txt);
#region comparison
if (Txt == "MR")
{
Debug.Log("Move Right");
}
else if (Txt == "MM")
{
Debug.Log("move middle");
}
else if (Txt == "ML")
{
Debug.Log("move left");
}
else if (Txt == "J")
{
Debug.Log("jump");
}
else if (Txt == "M")
{
Debug.Log("menu");
}
else if (Txt == "Q")
{
Debug.Log("quit");
}
#endregion
}
}
I think the code doesn't store the value of the Input field in the String properly and therefore can't be compared.
First of all the == operator is used to compare the reference identity. The Equals() method compares the content.
Change your code using Equals() method like:
Make sure to bind/link the variable inputFieldInMainUi to the input field in your UI. I'm not familiar with Unity3D, but there should be an option to link the variable inputFieldInMainUi to the actual field.
Lastly try debugging and put a breakpoint at the line where you assign a value to Txt, make sure this variable contains the string-value that you want to compare to