コガネブログ

平日更新を目標にUnityやC#、Visual Studioなどのゲーム開発アレコレを書いていきます

【Unity】【Arduino】Unity エディタ再生中に LED を光らせる

スクリプト

Arduino

void setup()
{
  Serial.begin( 9600 );
  pinMode( 13, OUTPUT );
}

void loop()
{
  if ( Serial.available() <= 0 ) return;

  char data = Serial.read();
  int num = data == '1' ? HIGH : LOW;
  digitalWrite( 13, num );
  Serial.flush();
}

Unity

using System.IO.Ports;
using UnityEditor;

public static class Example
{
    [InitializeOnLoadMethod]
    private static void Init()
    {
        var serial = new SerialPort( "COM3", 9600 );
        serial.Open();

        EditorApplication.playmodeStateChanged = () =>
        {
            var isPlaying   = EditorApplication.isPlaying;
            var str         = isPlaying ? "1" : "0";

            serial.Write( str );
        };
    }
}