首先在场景中创建UIDocument,如图:
其次在工程中创建UIDocument的Source Asset,如图:
这里我把这个Source Asset重新命名为VectorApiTest并把它指定给场景中的UIDocument。如图:
双击VectorApiTest文件进行编辑,首先选择VectorApiTest.uxml根对象,勾选Match Game View,如图:
然后添加一个可视元素,命名为Background,并设置尺寸,如图:
好了,开始写代码。创建一个继承VisualElement的类BezierConnect,脚本内容入下:
using UnityEngine;
using UnityEngine.UIElements;
public class BezierConnet : VisualElement
{
Vector2 pStart;
Vector2 pEnd;
Color color;
float width;
public BezierConnet(Vector2 pStart, Vector2 pEnd, Color color, float width)
{
this.pStart = pStart;
this.pEnd = pEnd;
this.color = color;
this.width = width;
generateVisualContent += OnGenerateVisualContent;
}
void OnGenerateVisualContent(MeshGenerationContext mgc)
{
Painter2D painter2D = mgc.painter2D;
painter2D.strokeColor = color;
painter2D.lineWidth = width;
painter2D.BeginPath();
painter2D.MoveTo(pStart);
float x = (pStart.x + pEnd.x) * 0.5f;
Vector2 p1 = new Vector2(x, pStart.y);
Vector2 p2 = new Vector2(x, pEnd.y);
painter2D.BezierCurveTo(p1, p2, pEnd);
painter2D.Stroke();
}
}
再创建一个PaintTest类,脚本内容入下:
using UnityEngine;
using UnityEngine.UIElements;
[RequireComponent(typeof(UIDocument))]
public class PaintTest : MonoBehaviour
{
UIDocument doc;
void Start()
{
doc = GetComponent<UIDocument>();
VisualElement element = doc.rootVisualElement.Q("Background");
element.Add(new BezierConnet(new Vector2(100, 100), new Vector2(200, 200), Color.red, 3));
element.Add(new BezierConnet(new Vector2(200, 300), new Vector2(400, 200), Color.blue, 5));
}
}
这个脚本挂到场景中UIDocument那个物体上去,如图:
好了,运行起来看看吧。如果一切顺利,结果入下: