Search Unity

Preview UI/Canvas based prefab

Discussion in 'UGUI & TextMesh Pro' started by MrDizzle26, Mar 2, 2022.

  1. MrDizzle26

    MrDizzle26

    Joined:
    Feb 8, 2015
    Posts:
    36
    Unity allows us to see the 3D elements of a prefab in its inspector window. But this doesn't seem possible to do for UI/Canvas related elements?

    upload_2022-3-2_18-52-17.png

    We are trying to create a UI prefab picker for our project, and not being able to preview the UI prefab is a major drawback and time-sync.

    The two solutions I can think of seem pretty flawed. One involves adding a reference to a screenshot of the UI prefab and displaying that, but this isn't optimal as the image would need to be updated for each change.

    The other would be to make something similar to the inbuilt 3D preview, by dynamically adding the prefab to a scene with a canvas and camera and rendering the result to a render texture, but I'm not even sure that's possible in Unity's editor API.



    Any advice would be much appreciated!
     
  2. giantkilleroverunity3d

    giantkilleroverunity3d

    Joined:
    Feb 28, 2014
    Posts:
    383
    Check this out:
     
  3. MrDizzle26

    MrDizzle26

    Joined:
    Feb 8, 2015
    Posts:
    36
    Thanks, but this suffers from my first solution's problem of the images becoming out of date, might go with this solution though!
     
  4. gop

    gop

    Joined:
    May 12, 2015
    Posts:
    1
    It seems I found a way to render canvas prefab to texture in editor:
    Code (CSharp):
    1.  
    2. var previewRender = new PreviewRenderUtility();
    3. previewRender.camera.backgroundColor = Color.grey;
    4. previewRender.camera.clearFlags = CameraClearFlags.SolidColor;
    5. previewRender.camera.cameraType = CameraType.Game;
    6. previewRender.camera.farClipPlane = 1000f;
    7. previewRender.camera.nearClipPlane = 0.1f;
    8.                
    9. previewRender.BeginStaticPreview(new Rect(0.0f, 0.0f, 1080.0f / 4.0f, 1920.0f / 4.0f));
    10.  
    11. var canvasInstance = previewRender.InstantiatePrefabInScene(gameObject).GetComponent<Canvas>();
    12. canvasInstance.renderMode = RenderMode.ScreenSpaceCamera;
    13. canvasInstance.worldCamera = previewRender.camera;
    14.  
    15. previewRender.Render();
    16.                
    17. var texture = previewRender.EndStaticPreview();
    18.                
    19. previewRender.camera.targetTexture = null;
    20. previewRender.Cleanup();
    21.  
    And then you can use this texture anywhere in your editor scripts:
    Image Pasted at 2022-9-15 18-09.jpg
     
    c2316339940 and y_fujita like this.