Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

UIElements how to preview sprites and prefabs in a custom editor?

Discussion in 'UI Toolkit' started by Sangemdoko, Jan 9, 2020.

  1. Sangemdoko

    Sangemdoko

    Joined:
    Dec 15, 2013
    Posts:
    220
    Hi I'm trying to preview my sprite icon when I change it in my custom editor. The problem is that I can't seem to find a way to only display the selected sprite, I display the entire texture instead.

    I assign the sprite texture as so:
    Code (CSharp):
    1. icon.style.backgroundImage = new StyleBackground(sprite.texture);
    Since StyleBackground does not take a sprite input I'm not sure how to display it.
    There is also the scaleToFit problem I do not know how to solve for non-square sprites.
    And I need to make sure it works with the custom sprites shapes made using the sprite editor (or by going Create -> Sprites -> ...)

    So right now I have:
    upload_2020-1-9_10-0-21.png
    But essentially I would like the same thing as displayed in the object picker:
    upload_2020-1-9_10-1-21.png

    Can anyone give me some advice?

    I would also like to do the same for Prefabs
    upload_2020-1-9_10-4-30.png
    but I'm not even sure where to start.

    Thank you for your time
     
  2. Sangemdoko

    Sangemdoko

    Joined:
    Dec 15, 2013
    Posts:
    220
    I found the solution. Turns out unity provides a static to get preview Textures.

    Code (CSharp):
    1. var texture = new StyleBackground(AssetPreview.GetAssetPreview(sprite));
    2. objectPreview.style.unityBackgroundScaleMode = new StyleEnum<ScaleMode>(ScaleMode.ScaleToFit);
    3. objectPreview.style.backgroundImage = texture;
    GetAssetPreview is asynchronous, so I simply refresh the visual element until it returns a preview.

    Here is how it looks:
    upload_2020-1-9_11-8-50.png
     
  3. jonathanma_unity

    jonathanma_unity

    Unity Technologies

    Joined:
    Jan 7, 2019
    Posts:
    229
    Hi,

    I'm glad you found the solution I just want to add that the style have implicit operator that you can use.
    Instead of :
    Code (CSharp):
    1. objectPreview.style.unityBackgroundScaleMode = new StyleEnum<ScaleMode>(ScaleMode.ScaleToFit);
    You can do :
    Code (CSharp):
    1. objectPreview.style.unityBackgroundScaleMode = ScaleMode.ScaleToFit;
    Enjoy!