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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Discussion The difference between Texture2D and Sprite in showing 2D Image

Discussion in '2D' started by wechat_os_Qy07nQhejWh67PEhCj6KWtoFE, Jan 6, 2023.

  1. wechat_os_Qy07nQhejWh67PEhCj6KWtoFE

    wechat_os_Qy07nQhejWh67PEhCj6KWtoFE

    Joined:
    Dec 30, 2022
    Posts:
    4
    I'm trying to load a local image and apply it to a UI.Image at runtime. The Question is that I can apply both texture2d and sprite to a Image in a similar way.
    For texture2d:
    Code (CSharp):
    1. var bytes = File.ReadAllBytes(imgPath);
    2.  
    3. var texture = new Texture2D(2, 2);
    4. if (texture.LoadImage(buffer)){
    5.         image.material.mainTexture = texture;
    6. }
    For sprite:
    Code (CSharp):
    1. var bytes = File.ReadAllBytes(imgPath);
    2.  
    3. var texture = new Texture2D(2, 2);
    4. if (texture.LoadImage(buffer)){
    5.         var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
    6.         image.sprite = sprite;
    7. }
    Both can achieve loading the task of loading local image, I wonder what is the difference and which way is better.
     
  2. DragonCoder

    DragonCoder

    Joined:
    Jul 3, 2015
    Posts:
    1,527
    With such a simple setup, the sprite renderer will likely do exactly the same. In the end the GPU always renders based on a material.
    Sprites exist due to the convenience features they offer like being 2D animatable (with the package) or used in UI in various ways.