1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【初心者向け】Revit API入門:壁の数を数えるC#アドイン

Posted at

Revit APIを使ったC#アドインの基本を、初心者向けにわかりやすく解説します。
今回は「モデル内の壁の数を数えて表示する」シンプルな例で学びます。

前提条件

  • Visual Studio(C#が書ける環境)
  • Revit(APIを使うので必須)
  • Revit APIの参照追加
    • RevitAPI.dllRevitAPIUI.dll をプロジェクトに追加

コード例

using Autodesk.Revit.DB;       // モデル操作用
using Autodesk.Revit.UI;       // UI操作用
using Autodesk.Revit.Attributes; // Transaction管理用

namespace RevitAPIBeginner
{
    [Transaction(TransactionMode.Manual)] // モデル変更時に必要
    public class CountWallsCommand : IExternalCommand
    {
        public Result Execute(
            ExternalCommandData commandData, 
            ref string message, 
            ElementSet elements)
        {
            // 現在開いているドキュメントを取得
            Document doc = commandData.Application.ActiveUIDocument.Document;

            // モデル内の壁(Wall)を集める
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            collector.OfClass(typeof(Wall)); // Wallクラスのみを抽出

            int wallCount = collector.GetElementCount(); // 壁の数をカウント

            // 結果をダイアログで表示
            TaskDialog.Show("Wall Count", "壁の数は " + wallCount + " です。");

            return Result.Succeeded;
        }
    }
}

コード解説

1. using 名前空間

using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;
  • DB → モデル要素を操作
  • UI → ダイアログや画面操作
  • Attributes → Transactionなどの設定

2. クラスとインターフェース

public class CountWallsCommand : IExternalCommand
  • Revitアドインは IExternalCommand を実装する
  • Execute メソッドがRevit上で呼ばれる

3. Transaction

[Transaction(TransactionMode.Manual)]
  • モデルを変更するときに必須

  • 今回は数えるだけなので不要でも動作するが、基本として付けておくと良い

4. ドキュメント取得

Document doc = commandData.Application.ActiveUIDocument.Document;
  • 現在開いているRevitモデル(.rvtファイル)を取得
  • これを使って要素を読み書きする

5. 要素収集

FilteredElementCollector collector = new FilteredElementCollector(doc);
collector.OfClass(typeof(Wall));
  • モデル内の要素を集める
  • OfClass で特定クラス(今回はWall)に絞る

6. 数の取得

int wallCount = collector.GetElementCount();
  • 集めた要素の数をカウント

7. 結果表示

TaskDialog.Show("Wall Count", "壁の数は " + wallCount + " です。");
  • Revit上にダイアログ表示
  • デバッグや確認に便利

ポイントまとめ

  • Document → Element → 操作 の流れで理解すると分かりやすい
  • FilteredElementCollector で要素を絞るのが基本
  • モデル変更時は必ず Transaction を使う
  • 結果表示には TaskDialog が便利
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?