Skip to content

Instantly share code, notes, and snippets.

@saguiitay
Created October 10, 2022 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saguiitay/fdc86365ffb4ee7aa9c7b5e27afc9707 to your computer and use it in GitHub Desktop.
Save saguiitay/fdc86365ffb4ee7aa9c7b5e27afc9707 to your computer and use it in GitHub Desktop.
SVG in Unity
using Unity.VectorGraphics;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class BaseSvgScript : MonoBehaviour
{
[Multiline()]
public string svg = "...";
public int pixelsPerUnit;
public bool flipYAxis;
protected List<VectorUtils.Geometry> GetGeometries()
{
using var textReader = new StringReader(svg);
var sceneInfo = SVGParser.ImportSVG(textReader);
return VectorUtils.TessellateScene(sceneInfo.Scene, new VectorUtils.TessellationOptions
{
StepDistance = 10,
SamplingStepSize = 100,
MaxCordDeviation = 0.5f,
MaxTanAngleDeviation = 0.1f
});
}
}
using Unity.VectorGraphics;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class MeshSvgScript : BaseSvgScript
{
void Start()
{
List<VectorUtils.Geometry> geometries = GetGeometries();
var meshFilter = GetComponent<MeshFilter>();
Mesh mesh = meshFilter.mesh;
VectorUtils.FillMesh(mesh, geometries, pixelsPerUnit, flipYAxis);
var meshRenderer = GetComponent<MeshRenderer>();
meshRenderer.materials = new Material[] { new Material(Shader.Find("UI/Default")) };
}
}
using Unity.VectorGraphics;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class SpriteSvgScript : BaseSvgScript
{
void Start()
{
List<VectorUtils.Geometry> geometries = GetGeometries();
var sprite = VectorUtils.BuildSprite(geometries, pixelsPerUnit, VectorUtils.Alignment.Center, Vector2.zero, 128, flipYAxis);
GetComponent<SpriteRenderer>().sprite = sprite;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment