[Vector Graphics] Referencing SVG Assets via C# Scripts
Solution
Unity 2019.3.x - Unity 6.3.x
Published 22 days ago
After upgrading to Unity 6 and transitioning from raster formats to vector graphics, developers encounter errors when attempting to assign SVG assets to Texture2D fields in the Inspector, as the types are no longer directly compatible without specific importer configurations or the VectorImage class.
To directly reference vector assets in your script, the VectorImage type should be utilized. This class is part of the Unity.VectorGraphics package and is the standard for resolution-independent graphics in the UI Toolkit.
- Open the Package Manager and install the
Vector Graphicspackage. - In your script, add the
using Unity.VectorGraphics;namespace. - Declare a public VectorImage field to hold the reference.
- Drag the SVG asset into the Inspector slot for your script.
If you prefer to maintain compatibility with Texture2D fields, you must modify the asset’s import settings:
- Select the SVG asset in the Project window.
- In the Inspector, locate the SVG Importer component.
- Change the
Generated Asset TypefromVectortoTexture2D. - Click
Applyto re-import the asset as a rasterized texture.
Additional Tips
-
Using VectorImage is highly recommended for UI Toolkit projects as it prevents pixelation at varying screen resolutions.
-
When converting to
Texture2D, keep in mind that the resulting asset is no longer resolution-independent and will use more memory than the raw VectorImage. -
If you need to manipulate the vector data at runtime, you must use VectorImage as it provides access to the
Scenedata via theVectorUtilshelper class.
TL;DR
To reference SVG assets in C#, utilize the VectorImage type from the Vector Graphics package or configure the asset importer to output a Texture2D compatible with legacy scripts.
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
Content inspired by a Unity discussion post.