Search Unity

Load Texture2D from Resources as a Sprite

Discussion in 'Scripting' started by Ilingis, Sep 5, 2016.

Thread Status:
Not open for further replies.
  1. Ilingis

    Ilingis

    Joined:
    Dec 13, 2012
    Posts:
    63
    Is there an easy way to do this?

    This doesn't work as the program looks for Sprites only.

    var textures = Resources.LoadAll (("Textures"), typeof(Sprites));

    This doesn't work at all as there's a mismatch of data types.

    var textures = Resources.LoadAll (("Textures"), typeof(Texture2D)) as Sprite;

    Thanks in advance!
     
  2. SirNiklas

    SirNiklas

    Joined:
    Jun 7, 2015
    Posts:
    85
    You cannot convert a Texture2D into a Sprite because those two types have nothing in common.
    You need to utilize the Sprite.Create method.

    Your code snippets contain relatively many errors of which some give me the impression this might be being pseudo code.
    The type mismatch exception is thrown because Resources.LoadAll returns an array, so you can obviously not convert Texture2D[] into a Sprite.

    As far as I understand you want to load textures from a folder and produce sprites out of those.
    Code (CSharp):
    1. var textures = Resources.LoadAll<Texture2D>("Textures");
    2. var sprites = textures.Select(texture => Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(.5f, .5f)));
    You need to include the System.Linq namespace to get this to work. Select is a method which iterates through all items of an array and converts it into a new form (Texture2D to Sprite).
    The last argument of the Sprite.Create method "pivot" marks the center of the sprite which is important for transformations such as rotations.
     
  3. Ilingis

    Ilingis

    Joined:
    Dec 13, 2012
    Posts:
    63
    You cannot convert a Texture2D into a Sprite because those two types have nothing in common.

    How come? In the editor you can do it easily with TextureImporter.

    I was trying to solve this for many hours and eventually I found the function Sprite.Create, but it's not optimal for what I want. It creates a sprite with a 512x512 texture, which is odd. Can it be changed through script?

    Anyway, I already found a way how to do this properly with a WWW function. Thanks for your help.
     
  4. zhaozony

    zhaozony

    Joined:
    Jan 7, 2020
    Posts:
    29
    ```
    image.sprite = Resources.LoadAll(iconPath)[1] as Sprite;
    ```
    unity generate sprite resource together with texture. use load all to get them both.
     
    tonytopper, I_X_I and TheLowestAnimal like this.
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,474
    This is nearly a 6 year old thread you just necroed replying to a user whose last post was nearly 5 years ago.

    Your other posts are doing this too.

    Please, look at the dates of threads before you post.
     
Thread Status:
Not open for further replies.