1

I am making a game where you can type stuff into a text box and then things will happen onscreen, such as a box will move. Im using a script which will see what you wrote and depending on what you wrote it does something, e.g., if you type "hello" it will say hello in the debug log. I tried to do something like this:

using UnityEngine;
using TMPro;
public class TextToAction : MonoBehaviour
{
     public TextMeshPro Text;
     void Update()
     {
            if(Text.text = "hello")
            {
                    Debug.Log("hello");
            }
      }
}

but it wouldnt work. Any thoughts?

EpicRaisin
  • 328
  • 3
  • 9
  • 1
    You have `if (Text.text = "hello")` this is a common rookie mistake, you are testing there IF you can set Text,text to the word hello not if it contains hello.. You meant `if (Text.text == "hello")` – BugFinder Jan 26 '20 at 22:59
  • 1
    @BugFinder actually you should not even use `Text.text == "hello"`, the correct way would be to use `Text.text.Equals("hello")` (see [C# difference between == and Equals()](https://stackoverflow.com/q/814878/7111561)) – derHugo Jan 27 '20 at 07:04
  • Did either of these suggestions help? – Peter Smith Jan 28 '20 at 18:25

1 Answers1

1
using UnityEngine;
using TMPro;
public class TextToAction : MonoBehaviour
{
     public TextMeshProUGUI text;
     void Update()
     {
            if(text.text.Equals("hello"))
            {
                    Debug.Log("hello");
            }
      }
}

You were using an assignment operator

  • single = in a = b

instead you were expecting to perform a comparison

  • Use == instead: a == b

However, when comparing strings you should use string.Equals(string) instead:

  • a.Equals(b)
Chris Schaller
  • 13,704
  • 3
  • 43
  • 81
MysticalUser
  • 404
  • 5
  • 13