Search Unity

SerialPort connection, Unity stuck untill serial input is recived

Discussion in 'Scripting' started by Artifactx, Jul 21, 2012.

  1. Artifactx

    Artifactx

    Joined:
    Jul 20, 2012
    Posts:
    14
    Hello, I'm playing around with Serial input and Unity.

    Here is my code, it is very simple but I have a problem. As long as Unity haven't recived any input through the serial it is stuck and I'm unable to do anything in the the unity editor. Which means that I can't stop the the execution of the game or select any objects in the Hieracy, untill I send some input through the SerialPort.

    So my question is, what is the correct way of doing this? I have tried running it in a CoRoutine, but that didn't work out.

    Code (csharp):
    1. public class InputHandler : MonoBehaviour
    2. {
    3.     public static SerialPort sp = new SerialPort("COM3", 9600);
    4.  
    5.  // Use this for initialization
    6.  void Awake ()
    7.         {  
    8.            sp.Open();
    9.  }
    10.  
    11.  // Update is called once per frame
    12.  void Update ()
    13.     {
    14.         if (sp.IsOpen)
    15.         {
    16.             print(sp.ReadChar());
    17.         }
    18.  
    19.      }
    20. }
     
  2. karljj1

    karljj1

    Joined:
    Feb 17, 2011
    Posts:
    440
    Coroutines are run in the same thread so will block. You need either a none blocking way to check.the port or do the check.in a different thread.
     
  3. Artifactx

    Artifactx

    Joined:
    Jul 20, 2012
    Posts:
    14
    Yea kinda tried in a diffrent thread, it didn't really wanna react to the input if I did that.