コガネブログ

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

【Unity】【Arduino】Unity エディタ再生中や一時停止中に LED を光らせる

スクリプト

Arduino

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

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

  int data = Serial.read();
  
  digitalWrite( 13, ( data & 1 ) != 0 ? HIGH : LOW );
  digitalWrite( 12, ( data & 2 ) != 0 ? HIGH : LOW );

  Serial.flush();
}

Unity

using System;
using System.IO.Ports;
using UnityEditor;

public static class Example
{
    [Flags]
    private enum State
    {
        NONE    = 0, 
        PLAYING = 1 << 0, 
        PAUSED  = 1 << 1, 
    }

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

        EditorApplication.playmodeStateChanged = () =>
        {
            var isPlaying   = EditorApplication.isPlaying;
            var isPaused    = EditorApplication.isPaused;
            var state       = State.NONE;
            
            state |= isPlaying ? State.PLAYING : State.NONE;
            state |= isPaused  ? State.PAUSED  : State.NONE;
            
            serial.Write( new byte[] { ( byte )state }, 0, 1 );
        };
    }
}