버전: 2023.2+
이 예시는 벡터 API를 사용하여 에디터 및 런타임 UI에서 그래프를 만드는 방법을 보여줍니다.
이 예시에서는 VisualElement에 파이 차트를 생성하여 에디터 및 런타임 UI에 표시합니다.
이 예시에서 만든 완성된 파일은 이 GitHub 저장소에서 찾을 수 있습니다.
이 가이드는 Unity 에디터, UI 툴킷, C# 스크립팅에 익숙한 개발자를 위한 가이드입니다. 시작하기 전에 먼저 다음을 숙지하십시오.
벡터 API의 Arc 및 Fill 메서드를 사용하여 시각적 요소에 파이 차트를 그리는 C# 스크립트를 만듭니다.
pie-chart라는 폴더를 만들어 파일을 저장합니다.pie-chart 폴더에 다음 내용을 포함하는 PieChart.cs라는 C# 스크립트를 생성합니다.using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
[UxmlElement]
public partial class PieChart : VisualElement
{
float m_Radius = 100.0f;
float m_Value = 40.0f;
public float radius
{
get => m_Radius;
set
{
m_Radius = value;
}
}
public float diameter => m_Radius * 2.0f;
public float value {
get { return m_Value; }
set { m_Value = value; MarkDirtyRepaint(); }
}
public PieChart()
{
generateVisualContent += DrawCanvas;
}
void DrawCanvas(MeshGenerationContext ctx)
{
var painter = ctx.painter2D;
painter.strokeColor = Color.white;
painter.fillColor = Color.white;
var percentage = m_Value;
var percentages = new float[] {
percentage, 100 - percentage
};
var colors = new Color32[] {
new Color32(182,235,122,255),
new Color32(251,120,19,255)
};
float angle = 0.0f;
float anglePct = 0.0f;
int k = 0;
foreach (var pct in percentages)
{
anglePct += 360.0f * (pct / 100);
painter.fillColor = colors[k++];
painter.BeginPath();
painter.MoveTo(new Vector2(m_Radius, m_Radius));
painter.Arc(new Vector2(m_Radius, m_Radius), m_Radius, angle, anglePct);
painter.Fill();
angle = anglePct;
}
}
}
Editor라는 폴더를 만들어 파일을 저장합니다.Editor 폴더에 다음 내용을 포함하는 PieChartWindow.cs라는 C# 스크립트를 생성합니다.using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
public class PieChartWindow : EditorWindow
{
[MenuItem("Tools/PieChart Window")]
public static void ShowExample()
{
PieChartWindow wnd = GetWindow<PieChartWindow>();
wnd.titleContent = new GUIContent("PieChartWindow");
}
public void CreateGUI()
{
VisualElement root = rootVisualElement;
root.Add(new PieChart());
}
}
에디터 창에서 파이 차트를 확인하려면 메뉴에서 Tools > PieChart Window를 선택합니다.
SampleScene의 UIDocument 게임 오브젝트에 파이 차트를 추가합니다. 그러려면 먼저 pie-chart라는 폴더에 다음 내용을 포함하는 PieChartComponet.cs라는 C# 스크립트를 생성합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
[RequireComponent(typeof(UIDocument))]
public class PieChartComponent : MonoBehaviour
{
PieChart m_PieChart;
void Start()
{
m_PieChart = new PieChart();
GetComponent<UIDocument>().rootVisualElement.Add(m_PieChart);
}
}
런타임에서 파이 차트를 보려면 다음 과정을 수행하십시오.