Unity Dear ImGui - 基本使用教學
2025-02-17 21:39:22
#unity
#imgui
在上一篇文章中,我們介紹了如何導入 Dear ImGui 以及在 Unity 中進行基本設定與使用。
這篇文章將進一步說明如何透過兩種方式打開一個自訂視窗,並在視窗內加入可以互動的按鈕。
本文將展示以下兩種方法:
- 透過快捷鍵
- 透過 Navbar 按鈕
由於這邊文章有運用到中文字體,請搭配這篇:
1. 透過快捷鍵打開自訂視窗
我們可以利用 Unity 的 Input 監聽快捷鍵事件,來切換自訂視窗的顯示狀態。
以下範例示範如何使用 F1 鍵來切換自訂視窗,並在視窗中加入一個互動按鈕,點擊後更新按鈕計數器:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| using UImGui; using UnityEngine;
public class CustomWindowWithButton : MonoBehaviour { private bool showCustomWindow = false; private int buttonClickCount = 0;
private void Update() { if (Input.GetKeyDown(KeyCode.F1)) { showCustomWindow = !showCustomWindow; } }
private void OnEnable() { UImGuiUtility.Layout += DrawCustomWindow; }
private void OnDisable() { UImGuiUtility.Layout -= DrawCustomWindow; }
private void DrawCustomWindow(UImGui.UImGui uImGui) { if (!showCustomWindow) { return; }
ImGuiNET.ImGui.Begin("自訂視窗 (快捷鍵開啟)"); ImGuiNET.ImGui.Text("這是一個包含互動按鈕的自訂視窗!"); ImGuiNET.ImGui.Text($"按鈕已點擊次數:{buttonClickCount}");
if (ImGuiNET.ImGui.Button("點我一下")) { buttonClickCount++; }
ImGuiNET.ImGui.End(); } }
|
使用方式
- 將上述程式碼掛在場景中的一個 GameObject 上。
- 進入 Play Mode,按下 F1 鍵,即可開啟或關閉自訂視窗。
- 在視窗中點擊 「點我一下」 按鈕,查看計數器數值的更新。
2. 透過 Navbar 按鈕打開自訂視窗
除了使用快捷鍵,也可以透過介面上的 Navbar 按鈕讓使用者切換自訂視窗。
以下範例示範如何在 Navbar 中新增一個選單項目,點擊後打開/關閉自訂視窗,且視窗中同樣包含互動按鈕:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| using UImGui; using UnityEngine;
using UImGui; using UnityEngine;
public class NavbarWindowWithButton : MonoBehaviour { private bool showCustomWindow = false; private int buttonClickCount = 0;
private void OnEnable() { UImGuiUtility.Layout += DrawNavbar; UImGuiUtility.Layout += DrawCustomWindow; }
private void OnDisable() { UImGuiUtility.Layout -= DrawNavbar; UImGuiUtility.Layout -= DrawCustomWindow; }
private void DrawNavbar(UImGui.UImGui uImGui) { if (ImGuiNET.ImGui.BeginMainMenuBar()) { if (ImGuiNET.ImGui.BeginMenu("工具")) { if (ImGuiNET.ImGui.MenuItem("自訂視窗")) { showCustomWindow = !showCustomWindow; } ImGuiNET.ImGui.EndMenu(); } ImGuiNET.ImGui.EndMainMenuBar(); } }
private void DrawCustomWindow(UImGui.UImGui uImGui) { if (!showCustomWindow) { return; }
ImGuiNET.ImGui.Begin("自訂視窗 (Navbar 開啟)");
ImGuiNET.ImGui.Text("這是一個包含互動按鈕的自訂視窗!"); ImGuiNET.ImGui.Text($"按鈕已點擊次數:{buttonClickCount}");
if (ImGuiNET.ImGui.Button("點我一下")) { buttonClickCount++; }
ImGuiNET.ImGui.End(); } }
|
使用方式
- 將上述程式碼掛在場景中的一個 GameObject 上。
- 進入 Play Mode,在畫面上方的主選單列中,點擊 「自訂視窗」 按鈕,即可切換視窗的顯示狀態。
- 在視窗中點擊 「點我一下」 按鈕,計數器將會更新。