# Class Diagram Generator

Analyzes Unity C# scripts and generates UML-style diagrams for architectural overview.

{% embed url="<https://assetstore.unity.com/packages/tools/utilities/class-diagram-generator-323124>" %}

{% tabs %}
{% tab title="Overview" %}
Class Diagram Generator is a Unity Editor tool that bridges your C# code and PlantUML class diagrams in **both directions**.

**Forward (code → diagram).** It parses selected `.cs` files, extracts class structures, members, inheritance, interfaces, associations, and **actual method calls**, then produces either:

* A `.puml` file stored inside the project, or
* A shareable PlantUML web URL using compressed encoding.

**Reverse (diagram → code).** It can also import a `.puml` PlantUML class diagram and generate matching **C# script skeletons** under any folder of your project. Existing files are skipped by default to keep your work safe.

The tool is designed for fast structural and behavioral visualization of Unity projects without requiring external IDE plugins or static analysis tools. It runs entirely inside the Unity Editor and does not execute in builds.

<figure><img src="/files/ly6SJsGMO8pFREo6jEng" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="Installation" %}
Copy the following files into your Unity project:

```
Assets/ClassDiagramGenerator/Editor/ClassDiagramGenerator.cs
Assets/ClassDiagramGenerator/Editor/ScriptSelectionManager.cs
```

All files are located under an `Editor` folder, ensuring the tool is excluded from builds automatically.

After compilation, access the tool via:

```
Tools > Diagram Generator
```

No additional configuration is required.
{% endtab %}

{% tab title="Quick Start" %}

#### Forward workflow — generate a diagram from your code

1. Open **Tools → Diagram Generator**
2. In the **Selection** card, pick a folder or `.cs` file using the Object field, click **Scan**, or drag & drop scripts/folders into the drop zone
3. Curate the list using **Search**, **All**, **None**, or **Invert**
4. In the toolbar, choose the export format:
   * **File (.puml)**
   * **URL** (PlantUML server link)
5. Click **Generate Diagram**

If exporting as a file, the diagram is written to the configured output path and Unity refreshes the AssetDatabase automatically. If exporting as a URL, a compressed PlantUML link is generated and displayed below — click **Copy URL** for immediate browser preview.

#### Reverse workflow — generate C# skeletons from a diagram

1. Open **Tools → Diagram Generator**
2. Scroll to the **Import Diagram / Generate Skeleton** card
3. Pick a `.puml` file using the Object field, or browse for one outside the project
4. Set the **Scripts Output** folder where the generated `.cs` files should be written
5. Keep **Skip existing files** enabled (recommended) to protect your existing scripts
6. Click **Import Diagram & Generate Skeleton**

One `.cs` file is created per type, organized by namespace, with public/private/protected/internal modifiers preserved and method bodies stubbed with `throw new NotImplementedException();` so the project compiles immediately.
{% endtab %}

{% tab title="Workflow" %}
The tool follows a five-stage process for the forward workflow, plus a dedicated reverse pipeline.

**1. Script Selection**

Scripts are collected using `ScriptSelectionManager`, which scans folders recursively for `.cs` files. You can:

* Scan entire folders (or the whole `Assets/` tree)
* Add individual scripts via drag & drop
* Filter using search
* Toggle selection per file with **All / None / Invert**
* Click any path in the list to ping the asset in the Project window

Only selected scripts are processed during generation.

***

**2. Parsing**

Each script is read and processed using a regex-based parser (`RegexClassDiagramParser`). The parser extracts:

* Class, interface, struct, and enum declarations
* Base classes
* Implemented interfaces
* Fields
* Properties
* Methods
* Method parameters
* **Method calls within method bodies** (new in 2.3.1)
* Basic XML summary comments

Visibility modifiers are converted to UML symbols:

* `+` public
* `-` private
* `#` protected
* `~` internal

Stable modifiers like `{static}` and `{abstract}` are surfaced. Constructors are ignored to reduce noise.

***

**3. Relationship Detection**

Inheritance and interface implementation are rendered using UML arrows.

If **Include associations** is enabled, additional relationships are generated from:

* Field types
* Property types
* Method parameter types
* **Method calls extracted from method bodies** (new in 2.3.1) — these turn the diagram into a behavioral map of which class actually invokes which

Associations are only created when the referenced type exists in the selected set, and duplicate/self-references are prevented.

***

**4. Smart Association Labels (new in 2.3.1)**

Instead of rendering generic labels like `"field"` or `"property"` on association arrows, the tool now displays the **real member names** that link two types.

* Multiple relations between the same pair of types are merged into a **single arrow** with a combined label
* Labels show up to **5 members maximum**, with a `…` suffix when more are present
* Both structural (fields, properties, parameters) and behavioral (method calls) members appear in the label

Example arrow label: `_database, Initialize(), RefreshUi()`

***

**5. PlantUML Generation**

The `PlantUmlExporter` constructs a standard PlantUML class diagram block:

```
@startuml
...
@enduml
```

Namespaces are rendered as PlantUML packages. Inside a package, type names are local; relationship arrows use fully qualified names to keep PlantUML syntax happy. Generics are normalized to avoid syntax issues, and type names are stripped when necessary to prevent invalid dotted declarations.

When exporting as a URL, the diagram text is:

* UTF-8 encoded
* Deflate-compressed
* Base64-like encoded using PlantUML's scheme

and appended to:

```
https://www.plantuml.com/plantuml/uml/
```

***

**Reverse pipeline — Import & Skeleton**

When you click **Import Diagram & Generate Skeleton**, a separate two-stage pipeline runs:

1. **Import** — `PlantUmlDiagramImporter` parses the `.puml` file back into the same domain models used by the forward pipeline (`DiagramTypeModel`, `DiagramFieldModel`, `DiagramPropertyModel`, `DiagramMethodModel`, `DiagramParameterModel`).
2. **Skeleton generation** — `CSharpSkeletonGenerator` walks those models and writes one `.cs` file per type:
   * Files are organized by namespace
   * `using UnityEngine;` and `using System.Collections.Generic;` are added by default
   * Visibility modifiers, `static`, and `abstract` are preserved
   * Method bodies are stubbed with `throw new NotImplementedException();`
   * Existing files are skipped when **Skip existing files** is enabled
     {% endtab %}

{% tab title="Technical Notes" %}

Class Diagram Generator is implemented as a custom `EditorWindow` integrated into the Unity menu via a `[MenuItem]` attribute, on top of a clean layered architecture.

**Architecture Overview**

The codebase is split into four layers, each with a single responsibility:

* **Domain** — pure data models with no Unity dependency
  * `DiagramTypeModel`, `DiagramFieldModel`, `DiagramPropertyModel`, `DiagramMethodModel`, `DiagramParameterModel`
* **Application** — use-case services and abstractions
  * Services: `DiagramGenerationService`, `DiagramImportAndSkeletonService`
  * Abstractions: `IClassDiagramParser`, `IPlantUmlExporter`, `IClassDiagramImporter`, `ICodeSkeletonGenerator`
  * Request/result records: `GenerateDiagramRequest`, `GenerateDiagramResult`, `GenerateSkeletonRequest`, `GenerateSkeletonResult`
* **Infrastructure** — concrete implementations
  * Parsing: `RegexClassDiagramParser`
  * Export: `PlantUmlExporter`, `PlantUmlUrlEncoder`
  * Import: `PlantUmlDiagramImporter`
  * Generation: `CSharpSkeletonGenerator`
  * Scanning: `ScriptSelectionManager`, `ScriptEntry`
  * Utilities: `UnityAssetFileWriter`
* **Editor** — the single Unity-facing window
  * `ClassDiagramGeneratorWindow`

Every layer is interface-driven, so the parser, exporter, importer, and skeleton generator can be swapped or reused in other tooling.

**Parsing Strategy**

The parser does not rely on Roslyn or full semantic analysis. It performs text-based pattern matching using `Regex` rules:

* Class / interface / struct / enum detection via multiline regex
* Field, property, and method detection via grouped patterns
* **Method-call extraction** via a dedicated `MethodCallRegex` that scans method bodies; matches are stored on a per-type `LocalCalls` list and resolved against known types at export time
* Generic base types safely split using depth-aware parsing
* Generics stripped when generating UML arrows

This keeps the tool lightweight while providing reasonable coverage for typical Unity codebases.

**Skeleton Generation Strategy**

`CSharpSkeletonGenerator` produces clean, idiomatic C# files that compile out-of-the-box:

* One file per type, named after the type
* Folder structure mirrors the namespace
* Default `using` directives included
* Member order: fields → properties → methods
* `throw new NotImplementedException();` stubs in every method body so the project compiles immediately

**Performance**

Scanning is file-system based (`Directory.GetFiles`). Parsing time depends on:

* Number of selected scripts
* Size of source files
* Complexity of declarations
* Method-body length (since 2.3.1 the parser scans bodies for calls)

For typical Unity projects (under a few hundred scripts), generation is near-instant.
{% endtab %}

{% tab title="Limitations" %}
Class Diagram Generator uses regex-based parsing and does not perform full C# semantic analysis.

Not supported:

* Nested types beyond basic detection
* Advanced generic constraints
* Partial classes merged across files
* Complex property bodies
* Attributes parsing
* Method overloading differentiation
* Expression-bodied members
* Record types
* Full namespace resolution across imported references

The tool assumes conventional C# formatting. Method-call detection (added in 2.3.1) matches identifier-based call patterns inside method bodies; calls made via reflection, dynamic dispatch, or unusual syntax may not be picked up.

Large projects with thousands of scripts may experience slower scanning due to file system traversal. The generated URL relies on the public PlantUML server.

For the reverse workflow, the importer expects PlantUML files produced by Class Diagram Generator or following the same conventions (UML class blocks, package declarations for namespaces). Heavily customized PlantUML files may not round-trip cleanly.
{% endtab %}

{% tab title="FAQ" %}

<details>

<summary>Does this modify my scripts?</summary>

No. The forward workflow only reads `.cs` files and generates output. The reverse workflow only writes new `.cs` files into the **Scripts Output** folder you choose, and skips existing files by default.

</details>

<details>

<summary>Can I scan the whole project?</summary>

Yes. You can scan any folder under `Assets/`, including the project root via the **Scan Assets** button or by dropping the `Assets/` folder into the drop zone.

</details>

<details>

<summary>Does it overwrite existing .puml files?</summary>

Yes, if you export to the same output path.

</details>

<details>

<summary>Does it overwrite existing .cs files when generating skeletons?</summary>

No, not by default. The **Skip existing files** option is enabled by default and will leave any existing `.cs` file untouched, even if its name matches a type from the imported diagram. Disable the option only if you intentionally want to overwrite.

</details>

<details>

<summary>Why are some classes missing?</summary>

* The script was not selected.
* The file does not contain a standard `class` or `interface` declaration matching the regex pattern.
* The code formatting is non-standard.

</details>

<details>

<summary>Why does an arrow show only some of the member names?</summary>

* Association labels are capped at **5 members maximum** to keep diagrams readable. If more than 5 members link the same two classes, the label ends with `…`. The full list is preserved in the underlying model — only the rendered label is truncated.

</details>

<details>

<summary>Can it export PNG or SVG directly?</summary>

No. The tool generates PlantUML text or a PlantUML web URL. Image export must be performed externally using PlantUML tools.

</details>

<details>

<summary>Why am I seeing PlantUML syntax errors?</summary>

Ensure that generated type names were not manually modified. The generator normalizes generics and references to minimize syntax issues, and uses local names inside `package` blocks while keeping fully qualified names for arrows.

</details>

<details>

<summary>Can I detect calls made via reflection or <code>SendMessage</code>?</summary>

No. Method-call detection (since 2.3.1) is based on identifier patterns in method bodies. Reflection (`MethodInfo.Invoke`), `SendMessage`, `BroadcastMessage`, and dynamic dispatch are not resolved.

</details>
{% endtab %}
{% endtabs %}

***

{% content-ref url="/spaces/u6FKPRtV6vGPNteP2vic/pages/WRI8HaHApRrkI9V2T4FD" %}
[Class Diagram Generator Changelog](/julestools-docs/changelog/readme-3.md)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://julestools.gitbook.io/julestools-docs/documentation/tools/class-diagram-generator.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
