• Stars
    star
    304
  • Rank 137,274 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate preview textures (thumbnails) for your GameObject's or materials on the fly in Unity

Unity Runtime Preview Generator

Available on Asset Store: https://assetstore.unity.com/packages/tools/camera/runtime-preview-generator-112860

Forum Thread: https://forum.unity.com/threads/runtime-preview-thumbnail-generator-open-source.500194/

Discord: https://discord.gg/UJJt549AaV

Support the Developer β˜•

This plugin helps you generate preview textures (thumbnails) for your GameObjects or materials in Texture2D format on the fly.

FEATURES

  • Supports perspective and orthographic projections
  • Supports transparent background
  • Customizable preview direction and background color

INSTALLATION

There are 5 ways to install this plugin:

  • import RuntimePreviewGenerator.unitypackage via Assets-Import Package
  • clone/download this repository and move the Plugins folder to your Unity project's Assets folder
  • import it from Asset Store
  • (via Package Manager) add the following line to Packages/manifest.json:
    • "com.yasirkula.runtimepreviewgenerator": "https://github.com/yasirkula/UnityRuntimePreviewGenerator.git",
  • (via OpenUPM) after installing openupm-cli, run the following command:
    • openupm add com.yasirkula.runtimepreviewgenerator

HOW TO

There are 2 main functions and on Unity 2018.2 or newer, their async variants:

public static Texture2D GenerateMaterialPreview( Material material, PrimitiveType previewPrimitive, int width = 64, int height = 64 );
public static Texture2D GenerateModelPreview( Transform model, int width = 64, int height = 64, bool shouldCloneModel = false, bool shouldIgnoreParticleSystems = true );

// !!! Async versions use AsyncGPUReadback.Request so they won't work on all platforms or Graphics APIs !!!
public static void GenerateMaterialPreviewAsync( Action<Texture2D> callback, Material material, PrimitiveType previewPrimitive, int width = 64, int height = 64 );
public static void GenerateModelPreviewAsync( Action<Texture2D> callback, Transform model, int width = 64, int height = 64, bool shouldCloneModel = false, bool shouldIgnoreParticleSystems = true );

RuntimePreviewGenerator.GenerateMaterialPreview function generates thumbnail for a material using a primitive object whereas RuntimePreviewGenerator.GenerateModelPreview function generates thumbnail for a GameObject (can be either a prefab or a scene object).

The width and height parameters define the size of the thumbnail texture. To guarantee a clear shot from the model in GenerateModelPreview function, the model is moved far away from the origin of the world (if it is not static) and then returned to its original position after the thumbnail is generated (this effect won't be visible to any scene cameras).

If shouldCloneModel parameter in GenerateModelPreview function is set to true, the model is instantiated (cloned) and the clone is used to create the thumbnail texture. This parameter is automatically set to true for prefabs. Unless you absolutely do not want your scene object to be moved, keep it as false for increased performance.

When the model has a child Particle System, the returned thumbnail may look empty. That's because Particle Systems usually have ridiculously large bounds and the camera needs to zoom out a lot to compensate that. Therefore, by default, Particle Systems are ignored while capturing thumbnails. You can set shouldIgnoreParticleSystems to false to override this behaviour.

There are also 2 variants for these functions that use replacement shaders while rendering the thumbnails (see: https://docs.unity3d.com/Manual/SL-ShaderReplacement.html) (URP and HDRP aren't supported). These functions are:

public static Texture2D GenerateMaterialPreviewWithShader( Material material, PrimitiveType previewPrimitive, Shader shader, string replacementTag, int width = 64, int height = 64 );
public static Texture2D GenerateModelPreviewWithShader( Transform model, Shader shader, string replacementTag, int width = 64, int height = 64, bool shouldCloneModel = false, bool shouldIgnoreParticleSystems = true );

// !!! Async versions use AsyncGPUReadback.Request so they won't work on all platforms or Graphics APIs !!!
public static void GenerateMaterialPreviewWithShaderAsync( Action<Texture2D> callback, Material material, PrimitiveType previewPrimitive, Shader shader, string replacementTag, int width = 64, int height = 64 );
public static void GenerateModelPreviewWithShaderAsync( Action<Texture2D> callback, Transform model, Shader shader, string replacementTag, int width = 64, int height = 64, bool shouldCloneModel = false, bool shouldIgnoreParticleSystems = true );

There are a few options to customize the generated thumbnails:

  • RuntimePreviewGenerator.PreviewRenderCamera: (default: null) lets you use your own camera for rendering the thumbnails instead of an internal camera that is automatically generated by RuntimePreviewGenerator. This is useful when you want to render thumbnails with some post-processing effects applied. You can set it to null to continue using the internal camera
  • RuntimePreviewGenerator.PreviewDirection: (default: Vector3(-1,-1,-1)) the direction that the camera will face relative to the previewed object's forward axis. So, a value of Vector3(0,0,-1) will create thumbnails from directly in front of the previewed object whereas a value of Vector3(0,0,1) will create thumbnails from behind the previewed object
  • RuntimePreviewGenerator.Padding: (default: 0) additional % padding applied to the edges of the thumbnail texture. The accepted value range is (-0.25,0.25). If there is too much space at the edges of the thumbnails, you can enter a negative value
  • RuntimePreviewGenerator.BackgroundColor: (default: Color(0.3,0.3,0.3,1)) background color of the thumbnail texture. If alpha value is less than 1, generated textures will be semi-transparent (or completely transparent, if alpha=0). Note that transparent textures consume more memory than opaque textures. In addition, some built-in transparent shaders like "Legacy Shaders/Transparent/Diffuse" may not render correctly on transparent backgrounds. There doesn't seem to be a fix for this issue; you can search "Unity Transparent Diffuse RenderTexture issue" to learn more
  • RuntimePreviewGenerator.OrthographicMode: (default: false) determines whether orthographic projection (true) or perspective projection (false) will be used while rendering the thumbnails. Thumbnails rendered with orthographic projection usually fill more pixels and are more center-aligned when compared to perspective projection
  • RuntimePreviewGenerator.UseLocalBounds: (default: false) determines whether the previewed object's world-space AABB bounds or local-space bounds are used to fit the object within the preview camera's frustum. Local bounds is more expensive to calculate but is expected to yield superior results (especially for complex objects) when orthographic projection is used. For perspective projection, world-space AABB bounds may yield better results
  • RuntimePreviewGenerator.RenderSupersampling: (default: 1) when not set to 1, thumbnails will be supersampled. For example, a value of 2.0 will render the thumbnails at 2x resolution and then the results will be downscaled to the original resolution. Supersampling helps fix shadow issues and can help with anti-aliasing but it's more expensive to calculate and for values larger than 2.0, it can introduce more aliasing than it fixes
  • RuntimePreviewGenerator.MarkTextureNonReadable: (default: true) marks the generated texture as non-readable for better memory usage. If you plan to modify the texture later (e.g. GetPixels/SetPixels), set its value to false

Please note that procedurally generated textures are not automatically garbage collected (until scene changes), so you are recommended to call Destroy(thumbnailTexture) or DestroyImmediate(thumbnailTexture) after you no longer need a thumbnail.

Here are two example thumbnails, one with perspective projection and grey background and the other with orthographic projection and transparent background:

perspective orthographic

DEBUG_BOUNDS Mode: the location of the preview render camera is calculated using the Renderer bounds of the target object. If you want, you can uncomment the first line of the RuntimePreviewGenerator script to see the bounds in the preview Textures

FAQ

  • Rendered thumbnail is empty, why?

If shouldIgnoreParticleSystems parameter is set to false, child particle systems of the model may force the camera to zoom out a lot. Or, on SRPs, your Forward Renderer asset's Opaque Layer Mask and/or Transparent Layer Mask might be excluding layer 22 (preview objects are temporarily assigned to this layer).

  • Rendered thumbnail doesn't look correct, why?

If there are lighting issues and you're generating thumbnails in Awake, try Start instead. Otherwise, try disabling post-processing effects and see if it makes any difference. If it does, then you should temporarily disable post-processing while capturing thumbnails.

More Repositories

1

UnityIngameDebugConsole

A uGUI based console to see debug messages and execute commands during gameplay in Unity
C#
2,117
star
2

UnityAssetUsageDetector

Find usages of the selected asset(s) and/or Object(s) in your Unity project, i.e. list the objects that refer to them
C#
1,693
star
3

UnityRuntimeInspector

Runtime Inspector and Hierarchy solution for Unity for debugging and runtime editing purposes
C#
1,676
star
4

UnityNativeGallery

A native Unity plugin to interact with Gallery/Photos on Android & iOS (save and/or load images/videos)
Objective-C++
1,396
star
5

UnityBezierSolution

A bezier spline solution for Unity 3D with some utility functions (like travelling the spline with constant speed/time)
C#
1,153
star
6

UnityNativeShare

A Unity plugin to natively share files (images, videos, documents, etc.) and/or plain text on Android & iOS
C#
905
star
7

UnitySimpleFileBrowser

A uGUI based runtime file browser for Unity 3D (draggable and resizable)
C#
844
star
8

UnityDynamicPanels

Draggable, resizable, dockable and stackable UI panel solution for Unity 3D
C#
735
star
9

UnityNativeCamera

A native Unity plugin to take pictures/record videos with device camera on Android & iOS
C#
605
star
10

UnityNativeFilePicker

A native Unity plugin to import/export files from/to various document providers on Android & iOS
C#
277
star
11

UnityInspectPlus

Speeding up your Inspector workflow in Unity 3D
C#
254
star
12

UnityImageCropper

A uGUI based image cropping solution for Unity 3D
C#
207
star
13

UnityAndroidRuntimePermissions

A native Unity plugin to handle runtime permissions on Android M+
C#
194
star
14

UnityRuntimeSceneGizmo

Interactable runtime scene gizmo for uGUI
C#
175
star
15

UnitySimplePatchTool

Unity port of SimplePatchTool library to add patching support to standalone Unity applications
C#
163
star
16

UnitySimpleInput

An improvement over Unity's legacy Input system that allows you to use custom input providers like on-screen joysticks, UI buttons and d-pads
C#
157
star
17

UnityAdjustPivot

Adjust pivot point of an object in Unity without creating an empty parent object
C#
149
star
18

Unity360ScreenshotCapture

A simple script to capture 360Β° screenshots in-game with Unity
C#
142
star
19

SimplePatchTool

C# library for patching standalone applications with binary diff and self patching support
C#
132
star
20

UnityTextToTextMeshProUpgradeTool

Upgrade Text, InputField, Dropdown and TextMesh objects to their TextMesh Pro variants in Unity
C#
113
star
21

DownloadLinkGeneratorForGoogleDrive

Create list of files and their download links in a Google Driveβ„’ folder
HTML
109
star
22

UnityIonicIntegration

A guide to integrating Unity 3D content into an Ionic app and sending messages between them (for Android & iOS)(tested with Vuforia plugin)
Objective-C++
104
star
23

UnityMobileLocalizedAppTitle

Localize your Unity app's name and/or icon on Android & iOS
C#
102
star
24

UnityGridFramework

Open source Grid Framework for creating grid-based levels easily in Unity 3D
C#
94
star
25

UnitySimpleGDPRConsent

A Unity plugin to present GDPR consent dialogs to the users
C#
93
star
26

UnityTextureOps

A basic image processing plugin for Unity
C#
87
star
27

UnityChoiceOfGamesSaveManager

Save manager for 'Choice of Games' on Steam - Created with Unity 3D
C#
76
star
28

UnitySpeechToText

A native Unity plugin to convert speech to text on Android & iOS
C#
70
star
29

UnityRuntimeTexture

An abstraction layer on top of Texture2D.LoadImage to create Texture2D objects at runtime from raw PNG/JPEG data in Unity
C#
62
star
30

UnityDashedSpriteShape

Creating dashed (dotted) 2D Sprite Shapes in Unity
ShaderLab
62
star
31

UnityMobileRemoteControl

Control your Windows device from your phone
C#
59
star
32

UnityEditorGoogleDriveIntegration

Access your Google Driveβ„’ files from within Unity editor
C#
48
star
33

UnityHexicGame

Hexic puzzle game made with Unity 3D
ShaderLab
36
star
34

UnityGenericPool

A simple generic pooling script for Unity3D with a helper class
C#
36
star
35

UnitySpinningLoadingBars

3 different spinning loading bar prefabs for Unity's UI system
28
star
36

UnityFlatColorPalettes

A number of flat color palettes for Unity 3D
26
star
37

UnityEveryplaySaveToLocal

A helper script to save captured Everyplay videos to local file system on Android & iOS
Objective-C++
15
star
38

UnityOrderedUpdate

Receive Update callback(s) from anywhere and in any order in Unity!
C#
15
star
39

UnityAndroidStreamingAssets

A helper script to extract StreamingAssets to local file system on Unity Android
C#
10
star
40

DownloadLinkGeneratorForDropbox

Create list of files and their download links in a Dropbox folder
HTML
6
star
41

SecondHand

Global Game Jam entry
C#
5
star
42

GeometricSketchpadProject

Bilkent CS102 Course Project
Java
4
star
43

GreenHellMods

A number of mods created via ModAPI for Green Hell game
C#
4
star
44

.github

Default GitHub community health files for all my repositories
2
star
45

BubblesProject

Bilkent CS319 Course Project
Java
2
star