ArduinoのデータをUnityで使おうとしたときに"Uniduino"という便利なアセットがあるそうです。しかしこのアセットは有料らしいので、今回は無料で実現する方法です。

 動作環境
  • Windows10
  • Unity 2018.4.31f1 Personal
  • Visual Studio Community 2019 16.8.4
  • Arduino1.8.10
です。Unity2019.4.18f1では動作しませんでした。

Arduino側
 普通にSerial.printで出力します。末尾は改行します。
 シリアルのビットレート(115200)とシリアルポート(今回はCOM7)は後で使うので覚えておいてください。
  1. int val1 = analogRead(0);
  2. void setup() {
  3.   Serial.begin(115200);
  4. }

  5. void loop() {
  6.   val1 = analogRead(0);
  7.   Serial.print(val1);
  8.   Serial.println("");
  9.   delay(1000);
  10. }


Unity側
 まず、前提として"File"->"Build Setting"->"Player Settings"->"OtherSettings"->"Configuration"->"Api Compatibility Level*"を".NET 4.x"にします。
b


①表示部の設定
 Hirerarchyで右クリック"UI"->"Text"を選択します。
 作成できたTextをクリックし、見やすいように各パラメータを設定します。今回自分は↓の画像のように設定しました。
スクリーンショット 2021-02-02 221748
②C#の設定
 シリアルを行うためのプログラムをC#で実装します。"Project"->"Assets"で右クリック"Create"->"C# Script"でC#のファイルを作成しそれぞれ"SerialHandler","SerialLight"と名付けます。それぞれのファイルには↓のコードを入れます。
SerialHandler
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.IO.Ports;
  4. using System.Threading;

  5. public class SerialHandler : MonoBehaviour{
  6. public delegate void SerialDataReceivedEventHandler(string message);
  7. public event SerialDataReceivedEventHandler OnDataReceived;

  8. public string portName = "COM7"; // Arduino IDEで設定したポート
  9. public int baudRate = 115200;  // ビットレート

  10. private SerialPort serialPort_;
  11. private Thread thread_;
  12. private bool isRunning_ = false;

  13. private string message_;
  14. private bool isNewMessageReceived_ = false;

  15. void Awake(){
  16. Open();
  17. }

  18. void Update(){
  19. if (isNewMessageReceived_){
  20. OnDataReceived(message_);
  21. }
  22. isNewMessageReceived_ = false;
  23. }

  24. void OnDestroy(){
  25. Close();
  26. }

  27. private void Open(){
  28. serialPort_ = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
  29. serialPort_.Open();

  30. isRunning_ = true;

  31. thread_ = new Thread(Read);
  32. thread_.Start();
  33. }

  34. private void Close(){
  35. isNewMessageReceived_ = false;
  36. isRunning_ = false;

  37. if (thread_ != null && thread_.IsAlive){
  38. thread_.Join();
  39. }

  40. if (serialPort_ != null && serialPort_.IsOpen){
  41. serialPort_.Close();
  42. serialPort_.Dispose();
  43. }
  44. }

  45. private void Read(){
  46. while (isRunning_ && serialPort_ != null && serialPort_.IsOpen){
  47. try{
  48. message_ = serialPort_.ReadLine();
  49. isNewMessageReceived_ = true;
  50. }
  51. catch (System.Exception e){
  52. Debug.LogWarning(e.Message);
  53. }
  54. }
  55. }

  56. public void Write(string message){
  57. try{
  58. serialPort_.Write(message);
  59. }
  60. catch (System.Exception e){
  61. Debug.LogWarning(e.Message);
  62. }
  63. }
  64. }
SerialLight
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;

  5. public class SerialLight : MonoBehaviour{

  6. public SerialHandler serialHandler;
  7. public Text text;

  8. void Start(){
  9. serialHandler.OnDataReceived += OnDataReceived;
  10. }

  11. void Update(){

  12. }

  13. void OnDataReceived(string message){
  14. try{
  15. text.text = message;
  16. }
  17. catch (System.Exception e){
  18. Debug.LogWarning(e.Message);
  19. }
  20. }
  21. }

③プログラムの結び付け
 前項で書いたコードを実際に動くように結び付けていきます。まず。"SerialHandler"を①で作った"Hierarchy"->"Canvas"->"Text"にドラッグアンドドロップします。
 そうしたら"Text"をクリックし"Inspector"で開きます。そうしたら下の方にあるSerial Light (Script)で↓の画像のように設定します。
a

 また、"Hierarchy"->"Creare"->"Create Empty"を行い、"SerialHandler"という空オブジェクトを作成します。そうしたら、その空オブジェクトに②で作った"SerialHandler.cs"をドラッグアンドドロップをします。


④実行する
 Arduinoに書き込み、Unityのスタートボタンを押すと実行され画面に送られてきた数字が表示されます。