Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How do I use a PNG file in StreamingAssets folder?

Discussion in 'Scripting' started by Croes_C, Jun 20, 2023.

  1. Croes_C

    Croes_C

    Joined:
    Aug 18, 2015
    Posts:
    18
    Hello,

    I'm trying to use a .PNG file from the StreamingAssets folder as a Sprite.
    But I have no idea how to do this. I can only find people bringing it to a Texture2D but I need it as a Sprite.
    And haven't found anything on converting from Texture2D to Sprite.

    I'm also wondering about texture/sprites settings (Texture Type, Filter Mode, Compression, ....) for this file.

    Any suggestions?
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    A sprite is a texture. ;)

    Essentially, if you mean a sprite in the scene view, then it will be a GameObject that has a SpriteRenderer which references one or more Sprites which references a Texture2D. A texture asset can be set to "sprite" mode which optimizes it for use in the SpriteRenderer and opens up options such as including it in a spritesheet.

    Note that whatever you edit in the Inspector of the assets won't be available from StreamingAssets because these files are loaded at runtime, thus there is no asset importer. If you HAVE to load sprites from StreamingAssets at runtime they need to be textures and they should be loaded as Texture2D and then you create a Sprite instance and assign the texture to it.
     
  3. Croes_C

    Croes_C

    Joined:
    Aug 18, 2015
    Posts:
    18
    It gives me a: Cannot implicitly convert type 'UnityEngine.Texture2D' to 'UnityEngine.Sprite'
     
  4. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    don't convert/cast, assign
    more or less like so:

    Texture2D tex = (load from streaming assets);
    Sprite spr = new Sprite();
    spr.texture = tex;
     
  5. Croes_C

    Croes_C

    Joined:
    Aug 18, 2015
    Posts:
    18
    it won't let me do: spr.texture = tex;
    it's a {get} / read-only...
     
  6. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    Sorry, haven't been using Sprite for a while. You have to Create(..) a sprite and pass in the texture.
     
    Bunny83 likes this.
  7. Croes_C

    Croes_C

    Joined:
    Aug 18, 2015
    Posts:
    18
    Aaah! Awesome! It's working now! : )
    Thank you very much for the help!