Created
October 10, 2022 10:36
-
-
Save saguiitay/fdc86365ffb4ee7aa9c7b5e27afc9707 to your computer and use it in GitHub Desktop.
SVG in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) }; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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