Search Unity

How to load an SVG sprite into a SpriteRenderer?

Discussion in 'Scripting' started by ghtx1138, Feb 25, 2019.

  1. ghtx1138

    ghtx1138

    Joined:
    Dec 11, 2017
    Posts:
    114
    I've posted over on the Vector Graphics Preview Package forum but figured I'd ask here as well.
    https://forum.unity.com/threads/vector-graphics-preview-package.529845/page-11

    I am trying to load an imported SVG/sprite onto a SpriteRenderer in the hierarchy with script in the editor - but it does not work and there are no errors.

    I'm guessing there is no public API for setting the sprite property on a SpriteRenderer to an svg image? I can do it manually so I guess a private API method exists. Can it be done via Reflection? I'm confused because when the SVG image is imported a sprite symbol appears as a child - it is labelled as a Sprite and has a file extension of .svg

    Here is the code documenting my tests at setting the .sprite property in the editor.

    Any thoughts would be greatly appreciated.

    thanks!

    Code (CSharp):
    1. GUILayout.Space(50);
    2. EditorGUILayout.LabelField("Sprite Load Test", EditorStyles.boldLabel);
    3. if (GUILayout.Button("Load image"))
    4. {
    5.     // Load the asset
    6.     SVGImage sv = (SVGImage)AssetDatabase.LoadAssetAtPath("Assets/Sprites/HeadFront.svg", typeof(SVGImage));
    7.     Texture2D t = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/TestPng.png", typeof(Texture2D));
    8.     // add game object and components
    9.     GameObject moduleGo = new GameObject(); //create the game object
    10.     SpriteRenderer mySprite = moduleGo.AddComponent<SpriteRenderer>();
    11.     SVGImage mySvg = moduleGo.AddComponent<SVGImage>(); // "For simple SVG images simply place the SVGImage component on the GameObject." https://forum.unity.com/threads/unity-ui-svg-support-script.551254/
    12.     // doesn't seem to display svg at all
    13.     // set the .sprite property to the loaded asset
    14.     //mySvg.sprite = sv; // cannot convert from svgimage to sprite
    15.     //mySprite.sprite = sv; // Cannot convert SVG to Sprite
    16.     mySprite.sprite = Sprite.Create(t, new Rect(0, 0, t.width, t.height), Vector2.zero); // works from png texture
    17.     // mySprite.sprite = Sprite.Create(sv, new Rect(0, 0, t.width, t.height), Vector2.zero); // Cannot convert SVG to Sprite
    18.     //Debug.Log(t.name);
    19. }