Search Unity

Object Field with large preview image.

Discussion in 'UI Toolkit' started by Chris_Entropy, Mar 16, 2022.

  1. Chris_Entropy

    Chris_Entropy

    Joined:
    Apr 11, 2011
    Posts:
    202
    I want to create an Editor object field with UI Elements that shows a square preview image of the asset assigned to it, as it is possible with Editor IMGUI at the moment.
    What do I have to set up how to make this happen?
     
  2. sebastiend-unity

    sebastiend-unity

    Unity Technologies

    Joined:
    Nov 9, 2015
    Posts:
    184
    If you can get a preview image in a Texture/Texture2D, you can do one of the following for your UI Toolkit implementation:

    1. Create a
    VisualElement
    and set
    style.backgroundImage
    to the texture:

    Code (CSharp):
    1. Texture2D previewTexture = ...;
    2. VisualElement ve = new VisualElement { ... };
    3. ve.style.backgroundImage = previewTexture;
    or use an
    Image
    and set its
    image
    to the texture:

    Code (CSharp):
    1. Texture2D previewTexture = ...;
    2. Image im = new Image { image = previewTexture };
     
    Chris_Entropy likes this.
  3. Chris_Entropy

    Chris_Entropy

    Joined:
    Apr 11, 2011
    Posts:
    202
    Ok, would I then somehow implement the callbacks on the Image (or VisualElement with changed backgroundImage) that would give the image the functionality of an ObjectField, or would I attach the Image to the ObjectField element?
     
  4. sebastiend-unity

    sebastiend-unity

    Unity Technologies

    Joined:
    Nov 9, 2015
    Posts:
    184
    Oh yeah. So you could do a couple of things, among those:

    1. Create an InspectorElement that will hold:
    i. a PropertyField (that you bind to a property holding your asset)
    ii. a VisualElement of your choice (as mentioned in my previous reply)
    Then, write a callback that will be called when the property's value changes, so you will be able to update the element's backgroundImage or image when called. You specify that callback with PropertyField.RegisterValueChangeCallback().

    2. Write a custom property drawer (assuming you want to use your field in the inspector), that could be used for a specific attribute for a specific data type; that would let the editor take care of creating an InspectorElement for you and mostly everything else if you provide a binding path to your property (that holds the asset).
     
    Chris_Entropy likes this.
  5. watsonsong

    watsonsong

    Joined:
    May 13, 2015
    Posts:
    555
    I think the problem is the ObjectField behaviour is not the same with EditorGUI.PropertyField.
    The imgui will show large thumbnail if the height is enough.