0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Unity】使用可能なポート番号をインスペクターに一覧表示するAttribute

Posted at

はじめに

シリアル通信を行う際などに使用可能なポート番号がInspectorで一覧表示されたら便利だと思い実装しました。

実装

SerialPortNameAttribute.cs
using UnityEngine;

public class SerialPortNameAttribute : PropertyAttribute
{}
SerialPortNameEditor.cs
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(SerialPortNameAttribute))]
public class SerialPortNameEditor : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        List<string> ports = SerialPort.GetPortNames().ToList();
        ports.Sort((a,b) =>
        {
            return int.Parse(a.Replace("COM", "")) - int.Parse(b.Replace("COM",""));
        });
        
        int curPortIndex = 0;
        for (int i = 0; i < ports.Count; i++)
        {
            if (ports[i].Equals(property.stringValue)) curPortIndex = i;
        }
        
        curPortIndex = EditorGUI.Popup(position,"PortName",curPortIndex,ports.ToArray());
        property.stringValue = ports[curPortIndex];
    }
}

使い方

ポート番号を取得したいstring型のフィールドに[SerialPortName]を付与してください。
privateなフィールドの場合は[SerializeField]も同時に付与してください。

記述例
[SerializeField,SerialPortName]
private string portName;

使用イメージ
image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?