If function won't work when comparing strings sent from a micro-controller.

I am using a micro-controller with Unity through the extension Ardity to send messages to Unity. I am using the micro-controller’s accelerometer to determine whether the micro-controller is moving up, down or rotating left and right and then sending those words to Unity as strings. Unity is receiving the information and displaying ‘up’, ‘down’, etc in the debug console when I test it, but as soon as I compare the message to a string in an if statement, the if statement doesn’t work, even though no errors are identified.

I coded the micro-controller using Arduino IDE. If you would like, I can post that code as well.

Any help would be amazing. Thanks

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    void OnConnectionEvent(bool success)
    {
        if (success)
            Debug.Log("Connection established");
        else
            Debug.Log("Connection attempt failed or disconnection detected");
    }

    void OnMessageArrived(string msg)
    {
        Debug.Log(msg); // this works

        if (msg == "Right")
        {
            // move right
            // for example, I wrote Debug.Log("Working") here and it wouldn't work
        }

        else if (msg == "Left")
        {
            // move left
        }

        else if (msg == "Up")
        {
            // move Up
        }

        else if (msg == "Down")
        {
            // move down
        }
    }
}

Try this instead:

Debug.Log(">" + msg + "< Length: " + msg.Length);

Make sure there are no spaces or any other non-printable characters like new line or carriage return in that string. You could use msg = msg.Trim(); to remove any leading or trailing whitespace characters. Though if there are other characters it would not work.

Thankyou so much. I got it working and the function is now running. I used the code above to find the exact messages being sent and found the same number on every message which turned out to be a space. This meant that the messages weren’t equaling each other. I used the ‘msg = msg.Trim();’ code to remove the spaces and it worked perfectly.