Comparison between InputField text and the answer text doesn't work properly; Unity3d; C#

221 Views Asked by At

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.

2

There are 2 best solutions below

12
Tassisto On

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:

if (Txt.Equals("MR"))
{
    Debug.Log("Move Right");
}

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

Txt = inputFieldInMainUi.text.ToUpper();
0
Greg On

Thank you very much to everybody who tried to help me with my problem, I was now finally able to find a solution. If you are interested in what was the problem I try to describe it to you: At the top of every unity-C# scrip we find the using tags, I didn't know you had to use a special using TMPro tag and therefore wasn't able to define my Inputfield as TMP_Inputfield. I once again what to thank you for your time and support :)