title: Unity in C#: Serial communication with Arduino
body: <p>I am trying to do serial communication with Arduino to control LED by Unity in C#.</p>
  
  <p>These below are my codes copied from a sample link:</p>
  
  <p><strong>SerialHandler.cs</strong></p>
  
  <pre><code>using UnityEngine;
  using System.Collections;
  using System.IO.Ports;
  using System.Threading;
  
  public class SerialHandler : MonoBehaviour
  {
  public delegate void SerialDataReceivedEventHandler(string message);
  public event SerialDataReceivedEventHandler OnDataReceived;
  
  public string portName = "/dev/tty.usbmodem1421";
  public int baudRate    = 9600;
  
  private SerialPort serialPort_;
  private Thread thread_;
  private bool isRunning_ = false;
  
  private string message_;
  private bool isNewMessageReceived_ = false;
  
  void Awake()
  {
      Open();
  }
  
  void Update()
  {
      if (isNewMessageReceived_) {
          OnDataReceived(message_);
      }
  }
  
  void OnDestroy()
  {
      Close();
  }
  
  private void Open()
  {
      serialPort_ = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
      serialPort_.Open();
  
      isRunning_ = true;
  
      thread_ = new Thread(Read);
      thread_.Start();
  }
  
  private void Close()
  {
      isRunning_ = false;
  
      if (thread_ != null &amp;&amp; thread_.IsAlive) {
          thread_.Join();
      }
  
      if (serialPort_ != null &amp;&amp; serialPort_.IsOpen) {
          serialPort_.Close();
          serialPort_.Dispose();
      }
  }
  
  private void Read()
  {
      while (isRunning_ &amp;&amp; serialPort_ != null &amp;&amp; serialPort_.IsOpen) {
          try {
              if (serialPort_.BytesToRead &gt; 0) {
                  message_ = serialPort_.ReadLine();
                  isNewMessageReceived_ = true;
              }
          } catch (System.Exception e) {
              Debug.LogWarning(e.Message);
          }
      }
  }
  
  public void Write(string message)
  {
      try {
          serialPort_.Write(message);
      } catch (System.Exception e) {
          Debug.LogWarning(e.Message);
      }
  }
  }
  </code></pre>
  
  <p><strong>LedController.cs</strong></p>
  
  <pre><code>using UnityEngine;
  using System.Collections;
  
  public class LedController : MonoBehaviour
  {
  public SerialHandler serialHandler;
  
  void Update()
  {
      if ( Input.GetKeyDown(KeyCode.A) ) {
          serialHandler.Write("0");
      }
      if ( Input.GetKeyDown(KeyCode.S) ) {
          serialHandler.Write("1");
      }
  }
  }
  </code></pre>
  
  <p>However, when pressing the keyboard <code>A</code> and <code>S</code> to switch a LED on/off, it doesn't work.
  There is error message as I get.</p>
  
  <p><code>Object reference not set to an instance of an object</code></p>
  
  <p>That would be really awesome if wisdoms help me out!</p>
  
  <p>Thanks,</p>
  
  <p>m</p>