Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Bake material to texture script

Discussion in 'Scripting' started by Essential, Dec 5, 2011.

  1. Essential

    Essential

    Joined:
    Sep 8, 2011
    Posts:
    265
    I'm just wondering if anyone uses (or has used) the Bake Material To Texture script - http://www.unifycommunity.com/wiki/index.php?title=Bake_Material_to_Texture

    I've installed it but am having trouble getting it to work correctly. Seems to run fine for the most part except for me it's not showing a preview in the preview window and, more importantly, it's not completing the bake. It seems to only do a third of the texture. Every time I run it it's doing a different amount and section of the texture but never the completed thing.

    Seems very useful for mobile development if I can get it to work.
     
  2. TriplePAF

    TriplePAF

    Joined:
    Aug 19, 2009
    Posts:
    246
    Here is a js version that works with Unity 3 or 4:

    And could somebody so kind to upload it into the wiki because I have no user rights! Please ;)

    Code (csharp):
    1. class BakeMaterialSettings
    2.  
    3. {
    4.     private static var kEditorPrefsName = "BakeMaterialSettings";
    5.    
    6.     static var kBakingLayerShouldBeUnusedInScene = 30;
    7.     static var kStandardTexNames = new Array ("_MainTex", "_BumpMap", "_Detail", "_ParallaxMap", "_Parallax");
    8.  
    9.     var bakeAlpha = false;
    10.     var bakeMainTexAsWhite = false;
    11.     var minTextureResolution = 8;
    12.     var maxTextureResolution = 2048;
    13.  
    14.     var emptyScene = false;
    15.     var useCustomLights = false;
    16.     var ambient = Color.black;
    17.    
    18.     static var kLights = 3;
    19.     var enableLight = new boolean[kLights];
    20.     var colorLight = new Color[kLights];
    21.     var dirLight = new Vector2[kLights];
    22.    
    23.     function BakeMaterialSettings ()
    24.     {
    25.         Load ();
    26.     }
    27.    
    28.     function Load ()
    29.     {
    30.         bakeAlpha = EditorPrefs.GetBool(kEditorPrefsName + ".bakeAlpha");
    31.         bakeMainTexAsWhite = EditorPrefs.GetBool(kEditorPrefsName + ".bakeMainTexAsWhite");
    32.         minTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".minTextureResolution", 8);
    33.         maxTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".maxTextureResolution", 2048);
    34.  
    35.         emptyScene = EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene");
    36.         useCustomLights = EditorPrefs.GetBool(kEditorPrefsName + ".useCustomLights");
    37.         ambient.r = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.r");
    38.         ambient.g = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.g");
    39.         ambient.b = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.b");
    40.         ambient.a = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.a", 1.0f);
    41.        
    42.         for (var q = 0; q < kLights; ++q)
    43.         {
    44.             enableLight[q] = EditorPrefs.GetBool(kEditorPrefsName + ".enableLight" + q);
    45.             colorLight[q].r = EditorPrefs.GetFloat(kEditorPrefsName + ".color.r" + q, 0.5f);
    46.             colorLight[q].g = EditorPrefs.GetFloat(kEditorPrefsName + ".color.g" + q, 0.5f);
    47.             colorLight[q].b = EditorPrefs.GetFloat(kEditorPrefsName + ".color.b" + q, 0.5f);
    48.             colorLight[q].a = EditorPrefs.GetFloat(kEditorPrefsName + ".color.a" + q, 1.0f);
    49.             dirLight[q].x = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.x" + q);
    50.             dirLight[q].y = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.y" + q);
    51.         }
    52.     }
    53.    
    54.     function Save ()
    55.     {
    56.         EditorPrefs.SetBool(kEditorPrefsName + ".bakeAlpha", bakeAlpha);
    57.         EditorPrefs.SetBool(kEditorPrefsName + ".bakeMainTexAsWhite", bakeMainTexAsWhite);
    58.         EditorPrefs.SetInt(kEditorPrefsName + ".minTextureResolution", minTextureResolution);
    59.         EditorPrefs.SetInt(kEditorPrefsName + ".maxTextureResolution", maxTextureResolution);
    60.  
    61.         EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene", emptyScene);
    62.         EditorPrefs.SetBool(kEditorPrefsName + ".useCustomLights", useCustomLights);
    63.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.r", ambient.r);
    64.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.g", ambient.g);
    65.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.b", ambient.b);
    66.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.a", ambient.a);
    67.  
    68.         for (var q = 0; q < kLights; ++q)
    69.         {
    70.             EditorPrefs.SetBool(kEditorPrefsName + ".enableLight" + q, enableLight[q]);
    71.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.r" + q, colorLight[q].r);
    72.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.g" + q, colorLight[q].g);
    73.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.b" + q, colorLight[q].b);
    74.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.a" + q, colorLight[q].a);
    75.             EditorPrefs.SetFloat(kEditorPrefsName + ".dir.x" + q, dirLight[q].x);
    76.             EditorPrefs.SetFloat(kEditorPrefsName + ".dir.y" + q, dirLight[q].y);
    77.         }
    78.     }
    79. }
    80.  
    81. class BakeMaterial extends EditorWindow
    82. {
    83.     private static var kMateriBakeNodeName = "__MateriaBakeSetup";
    84.     private static var kWindowMinSize = Vector2 (300, 386);
    85.    
    86.     private static var settings : BakeMaterialSettings;
    87.     private static var visible : boolean = false;
    88.    
    89.     private var camera : GameObject;
    90.     private var plane : GameObject;
    91.     private var previewTexture : Texture;
    92.     private var lights : GameObject[] = new GameObject[BakeMaterialSettings.kLights];
    93.     private var stateChanged = false;
    94.    
    95.     private var texViewScrollPosition = Vector2.zero;
    96.     private var lastMaterial : Material;
    97.    
    98.     private var originalScene = "";
    99.    
    100.     private var scheduleBakeOnNextUpdate = false;
    101.  
    102.    
    103.     private function SetupScene ()
    104.     {
    105.         DestroyScene ();
    106.         var oldGo = GameObject.Find(kMateriBakeNodeName);
    107.         if (oldGo)
    108.             DestroyImmediate (oldGo);
    109.         camera = new GameObject (kMateriBakeNodeName, Camera);
    110.         plane = GameObject.CreatePrimitive (PrimitiveType.Plane);
    111.  
    112.         var cam = camera;
    113.         cam.camera.backgroundColor = Color.black;
    114.         cam.camera.clearFlags = CameraClearFlags.SolidColor;
    115.         cam.camera.orthographic = true;
    116.         cam.camera.orthographicSize = 5.0;
    117.         cam.camera.cullingMask = 1 << settings.kBakingLayerShouldBeUnusedInScene;
    118.        
    119.         plane.transform.parent = cam.transform;
    120.         plane.transform.position = Vector3.forward * 10.0;
    121.         plane.transform.rotation = Quaternion.Euler (0, 0, 180) * Quaternion.Euler (-90, 0, 0);
    122.         plane.layer = settings.kBakingLayerShouldBeUnusedInScene;
    123.        
    124.         for (var l in lights)
    125.         {
    126.             l = new GameObject ("Light", Light);
    127.             l.light.type = LightType.Directional;
    128.             l.light.cullingMask = 1 << settings.kBakingLayerShouldBeUnusedInScene;
    129.             l.transform.parent = cam.transform;
    130.             l.active = false;
    131.         }
    132.     }
    133.    
    134.     private function UpdateScene (m : Material)
    135.     {
    136.         for (q = 0; q < settings.kLights; ++q)
    137.         {
    138.             lights[q].active = settings.useCustomLights  settings.enableLight[q];
    139.             lights[q].light.color = settings.colorLight[q];
    140.             lights[q].transform.rotation =
    141.                 Quaternion.AngleAxis(settings.dirLight[q].x, Vector3.up) *
    142.                 Quaternion.AngleAxis(settings.dirLight[q].y, Vector3.right);
    143.         }
    144.        
    145.         if (settings.useCustomLights)
    146.             RenderSettings.ambientLight = settings.ambient;
    147.         else if (settings.emptyScene)
    148.             RenderSettings.ambientLight = Color.white;
    149.            
    150.         plane.renderer.material = m;
    151.     }
    152.        
    153.     private function DestroyScene ()
    154.     {
    155.         GameObject.DestroyImmediate (camera);
    156.         GameObject.DestroyImmediate (plane);
    157.         GameObject.DestroyImmediate (previewTexture);
    158.     }
    159.  
    160.     function UpdateMaterialPreview (m : Material) : RenderTexture
    161.     {
    162.         if (!m)
    163.             return;
    164.        
    165.         var saveAmbientLight = RenderSettings.ambientLight;
    166.         var saveMainTexture = m.mainTexture;
    167.         if (settings.bakeMainTexAsWhite)
    168.             m.mainTexture = null;
    169.    
    170.        
    171.         // setup
    172.         if (!camera)
    173.             SetupScene ();
    174.         camera.SetActiveRecursively(true);
    175.         UpdateScene (m);
    176.        
    177.         var res = FindLargestTextureResolution (plane.renderer.sharedMaterial, settings.minTextureResolution, settings.maxTextureResolution);
    178.         var rt = RenderCameraToRenderTexture (camera.camera, res.x, res.y);
    179.        
    180.         // restore
    181.         camera.SetActiveRecursively(false);
    182.         RenderSettings.ambientLight = saveAmbientLight;
    183.         m.mainTexture = saveMainTexture;
    184.        
    185.         previewTexture = rt;
    186.         return rt;
    187.     }
    188.    
    189.     function CaptureMaterial(m : Material)
    190.     {
    191.         var matAssetPath = AssetDatabase.GetAssetPath (m);
    192.         var assetPath = System.IO.Path.Combine (System.IO.Path.GetDirectoryName (matAssetPath), System.IO.Path.GetFileNameWithoutExtension (matAssetPath));
    193.  
    194.         var rt = UpdateMaterialPreview (m);
    195.         RenderTextureToPNG (rt, settings.bakeAlpha, assetPath + ".png");
    196.     }
    197.  
    198.     function OnEnable ()
    199.     {
    200.         if (!settings)
    201.             settings = new BakeMaterialSettings ();
    202.         SetupScene ();
    203.         visible = true;
    204.     }
    205.    
    206.     function OnDisable ()
    207.     {
    208.         DestroyScene ();
    209.         settings.Save ();
    210.         visible = false;
    211.     }
    212.  
    213.     static function GetTargetMaterial () : Material
    214.     {
    215.         return EditorUtility.InstanceIDToObject (Selection.activeInstanceID) as Material;
    216.     }
    217.  
    218.     function OnSelectionChange ()
    219.     {
    220.         Repaint ();
    221.     }
    222.  
    223.     function Update ()
    224.     {
    225.         var rebuildScene = false;
    226.         if (scheduleBakeOnNextUpdate)
    227.         {
    228.             Bake ();
    229.             scheduleBakeOnNextUpdate = false;
    230.             rebuildScene = true;
    231.         }
    232.        
    233.         if (originalScene == ""  EditorApplication.currentScene == "")
    234.             settings.emptyScene = true;
    235.            
    236.         if (settings.emptyScene  originalScene == ""  EditorApplication.currentScene != "")
    237.         {
    238.             DestroyScene ();
    239.             if (EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    240.             {
    241.                 originalScene = EditorApplication.currentScene;
    242.                 EditorApplication.NewScene ();
    243.             }
    244.             else
    245.                 settings.emptyScene = false;
    246.             rebuildScene = true;          
    247.         }
    248.         else if (!settings.emptyScene  originalScene != "")
    249.         {
    250.             EditorApplication.OpenScene (originalScene);
    251.             rebuildScene = true;
    252.             originalScene = "";
    253.         }
    254.        
    255.         if (rebuildScene)
    256.         {
    257.             SetupScene ();
    258.         }
    259.        
    260.         if (rebuildScene || stateChanged || !settings.emptyScene)
    261.         {
    262.             UpdateMaterialPreview (lastMaterial);
    263.             Repaint ();
    264.             stateChanged = false;
    265.         }
    266.     }
    267.    
    268.     function OnGUI ()
    269.     {
    270.         var material = GetTargetMaterial ();
    271.         if (lastMaterial != material)
    272.             UpdateMaterialPreview (material);
    273.         if (material)
    274.             lastMaterial = material;
    275.        
    276.         EditorGUILayout.BeginHorizontal();
    277.             EditorGUILayout.BeginVertical(GUILayout.MaxWidth(200));
    278.                 if (!(originalScene == ""  EditorApplication.currentScene == ""))
    279.                 {
    280.                     settings.emptyScene = !EditorGUILayout.BeginToggleGroup("Scene ligthing", !settings.emptyScene);
    281.                     EditorGUILayout.EndToggleGroup();
    282.                 }
    283.                 settings.useCustomLights = EditorGUILayout.BeginToggleGroup("Custom lighting", settings.useCustomLights);
    284.                 if (settings.useCustomLights)
    285.                 {
    286.                     EditorGUI.indentLevel = 1;
    287.                     settings.ambient = EditorGUILayout.ColorField("Ambient", settings.ambient);
    288.                     for (var q = 0; q < settings.kLights; ++q)
    289.                     {
    290.                         settings.enableLight[q] = EditorGUILayout.BeginToggleGroup("Light", settings.enableLight[q]);
    291.                         EditorGUI.indentLevel = 2;
    292.                             settings.colorLight[q] = EditorGUILayout.ColorField("Color", settings.colorLight[q]);
    293.                             settings.dirLight[q] = EditorGUILayout.Vector2Field("Direction", settings.dirLight[q]);
    294.                         EditorGUILayout.EndToggleGroup();
    295.                     }
    296.                 }
    297.                 EditorGUI.indentLevel = 0;
    298.                 EditorGUILayout.EndToggleGroup();
    299.                
    300.                 settings.bakeAlpha = EditorGUILayout.Toggle("Bake Alpha", settings.bakeAlpha);
    301.                 settings.bakeMainTexAsWhite = !EditorGUILayout.Toggle("MainTex", !settings.bakeMainTexAsWhite);
    302.                 settings.minTextureResolution = EditorGUILayout.IntField("Min Resolution", settings.minTextureResolution);
    303.                 settings.maxTextureResolution = EditorGUILayout.IntField("Max Resolution", settings.maxTextureResolution);
    304.                 settings.minTextureResolution = Mathf.Max(2, settings.minTextureResolution);
    305.                 settings.maxTextureResolution = Mathf.Max(settings.minTextureResolution, settings.maxTextureResolution);
    306.  
    307.                 EditorGUILayout.BeginHorizontal();
    308.                 if (GUILayout.Button("Bake"))
    309.                 {
    310.                     CaptureMaterial (lastMaterial);
    311.                 }
    312.                 if (GUILayout.Button("Bake Selected"))
    313.                 {
    314.                     scheduleBakeOnNextUpdate = true;
    315.                 }
    316.                 EditorGUILayout.EndHorizontal();
    317.                
    318.             EditorGUILayout.EndVertical();
    319.            
    320.             texViewScrollPosition = EditorGUILayout.BeginScrollView (texViewScrollPosition);
    321.                 var r = GUILayoutUtility.GetAspectRect(1.0f);
    322.                 if (previewTexture)
    323.                     EditorGUI.DrawPreviewTexture(r, previewTexture);
    324.             EditorGUILayout.EndScrollView();      
    325.         EditorGUILayout.EndHorizontal();
    326.        
    327.         if (GUI.changed)
    328.         {
    329.             stateChanged = true;
    330.         }
    331.     }
    332.    
    333.     @MenuItem("Custom/Bake Material ...", false, 5)
    334.     static function CreateBakeEditor()
    335.     {
    336.         var window : BakeMaterial = EditorWindow.GetWindow(BakeMaterial);
    337.         window.title = "Bake Material";
    338.         window.minSize = kWindowMinSize;
    339.         window.Show();
    340.     }
    341.  
    342.     @MenuItem("Custom/Bake Selected Materials", false, 4)
    343.     static function Bake()
    344.     {
    345.         var instanceIDs = Selection.instanceIDs;
    346.         var currentScene = EditorApplication.currentScene;
    347.    
    348.         var wasAlreadyVisible = BakeMaterial.visible;
    349.         var window : BakeMaterial = EditorWindow.GetWindow(BakeMaterial);
    350.        
    351.         if (window.settings.emptyScene)
    352.         {
    353.             if (!EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    354.                 return;
    355.             EditorApplication.NewScene ();
    356.         }
    357.        
    358.         window.SetupScene ();
    359.         for (var i in instanceIDs)
    360.         {
    361.             var m : Material = EditorUtility.InstanceIDToObject (i) as Material;
    362.             if (m)
    363.                 window.CaptureMaterial (m);
    364.         }
    365.         window.DestroyScene ();
    366.        
    367.         if (window.settings.emptyScene  currentScene)
    368.         {
    369.             EditorApplication.OpenScene (currentScene);
    370.         }
    371.        
    372.         if (!wasAlreadyVisible)
    373.             window.Close ();
    374.     }
    375.    
    376.     static function FindLargestTextureResolution (m : Material, minTexRes : int, maxTexRes : int) : Vector2
    377.     {
    378.         var res = Vector2 (minTexRes, minTexRes);
    379.         for (var n in BakeMaterialSettings.kStandardTexNames)
    380.         {
    381.             if (!m.HasProperty (n))
    382.                 continue;
    383.        
    384.             var t : Texture = m.GetTexture (n);
    385.             if (!t)
    386.                 continue;
    387.            
    388.             res.x = Mathf.Max (res.x, t.width);
    389.             res.y = Mathf.Max (res.y, t.height);
    390.         }
    391.         res.x = Mathf.Min (res.x, maxTexRes);
    392.         res.y = Mathf.Min (res.y, maxTexRes);
    393.         return res;
    394.     }
    395.    
    396.     static function RenderCameraToRenderTexture (cam : Camera, width : int, height : int) : RenderTexture
    397.     {
    398.         var rt = cam.camera.targetTexture;
    399.         if (rt  rt.width != width  rt.height != height)
    400.             DestroyImmediate(rt);
    401.         if (!rt)
    402.             rt = new RenderTexture (width, height, 24);
    403.         cam.camera.targetTexture = rt;
    404.         cam.camera.Render ();
    405.         return rt;
    406.     }
    407.    
    408.     static function RenderTextureToPNG (rt : RenderTexture, bakeAlpha : boolean, assetPath : String)
    409.     {
    410.         RenderTexture.active = rt;
    411.        
    412.         var screenShot = new Texture2D (rt.width, rt.height, bakeAlpha? TextureFormat.ARGB32 : TextureFormat.RGB24, false);
    413.         screenShot.ReadPixels (Rect (0, 0, rt.width, rt.height), 0, 0);
    414.        
    415.         RenderTexture.active = null;
    416.        
    417.         var bytes = screenShot.EncodeToPNG ();
    418.         System.IO.File.WriteAllBytes (assetPath, bytes);
    419.        
    420.         AssetDatabase.ImportAsset (assetPath, ImportAssetOptions.ForceUpdate);
    421.     }
    422. }
    423.  
     
  3. franmts

    franmts

    Joined:
    Oct 14, 2013
    Posts:
    10
    Has someone used this Script with version 4.2 of Unity ??

    For me neither this version or the one on the Wiki works. I select a unity's standard bumped specular material and when I press "Bake Material..." Unity crashes and closes the project. :neutral:

    I've tried using different shaders but nothing worked... Any insights on why it might not be working??
     
  4. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    882
    he existe somethinks similair

    i got
    ArgumentException: Invalid path
    System.IO.Path.GetDirectoryName (System.String path) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.IO/Path.cs:215)
    BakeMaterial.CaptureMaterial (UnityEngine.Material m) (at Assets/baketexture.js:193)
    BakeMaterial.OnGUI () (at Assets/baketexture.js:311)
    System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:222)
     
  5. Ippokratis

    Ippokratis

    Joined:
    Oct 13, 2008
    Posts:
    1,520
    4.5.2f1 compatible version.
    Many thanks to Rej.
    Save it in a js script.
    Use it from Menu-> Custom->Bake.

    Code (csharp):
    1. classBakeMaterialSettings
    2. {
    3. privatestaticvarkEditorPrefsName = "BakeMaterialSettings";
    4.  
    5. staticvarkBakingLayerShouldBeUnusedInScene = 30;
    6. staticvarkStandardTexNames = newArray ("_MainTex", "_BumpMap", "_Detail", "_ParallaxMap", "_Parallax");
    7.  
    8. varbakeAlpha = false;
    9. varbakeMainTexAsWhite = false;
    10. varminTextureResolution = 8;
    11. varmaxTextureResolution = 2048;
    12.  
    13. varemptyScene = false;
    14. varuseCustomLights = false;
    15. varambient = Color.black;
    16.  
    17. staticvarkLights = 3;
    18. varenableLight = newboolean[kLights];
    19. varcolorLight = newColor[kLights];
    20. vardirLight = newVector2[kLights];
    21.  
    22. functionBakeMaterialSettings ()
    23.  {
    24. Load ();
    25.  }
    26.  
    27. functionLoad ()
    28.  {
    29. bakeAlpha = EditorPrefs.GetBool(kEditorPrefsName + ".bakeAlpha");
    30. bakeMainTexAsWhite = EditorPrefs.GetBool(kEditorPrefsName + ".bakeMainTexAsWhite");
    31. minTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".minTextureResolution", 8);
    32. maxTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".maxTextureResolution", 2048);
    33.  
    34. emptyScene = EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene");
    35. useCustomLights = EditorPrefs.GetBool(kEditorPrefsName + ".useCustomLights");
    36. ambient.r = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.r");
    37. ambient.g = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.g");
    38. ambient.b = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.b");
    39. ambient.a = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.a", 1.0f);
    40.  
    41. for (varq = 0; q < kLights; ++q)
    42.  {
    43. enableLight[q] = EditorPrefs.GetBool(kEditorPrefsName + ".enableLight" + q);
    44. colorLight[q].r = EditorPrefs.GetFloat(kEditorPrefsName + ".color.r" + q, 0.5f);
    45. colorLight[q].g = EditorPrefs.GetFloat(kEditorPrefsName + ".color.g" + q, 0.5f);
    46. colorLight[q].b = EditorPrefs.GetFloat(kEditorPrefsName + ".color.b" + q, 0.5f);
    47. colorLight[q].a = EditorPrefs.GetFloat(kEditorPrefsName + ".color.a" + q, 1.0f);
    48. dirLight[q].x = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.x" + q);
    49. dirLight[q].y = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.y" + q);
    50.  }
    51.  }
    52.  
    53. functionSave ()
    54.  {
    55. EditorPrefs.SetBool(kEditorPrefsName + ".bakeAlpha", bakeAlpha);
    56. EditorPrefs.SetBool(kEditorPrefsName + ".bakeMainTexAsWhite", bakeMainTexAsWhite);
    57. EditorPrefs.SetInt(kEditorPrefsName + ".minTextureResolution", minTextureResolution);
    58. EditorPrefs.SetInt(kEditorPrefsName + ".maxTextureResolution", maxTextureResolution);
    59.  
    60. EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene", emptyScene);
    61. EditorPrefs.SetBool(kEditorPrefsName + ".useCustomLights", useCustomLights);
    62. EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.r", ambient.r);
    63. EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.g", ambient.g);
    64. EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.b", ambient.b);
    65. EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.a", ambient.a);
    66.  
    67. for (varq = 0; q < kLights; ++q)
    68.  {
    69. EditorPrefs.SetBool(kEditorPrefsName + ".enableLight" + q, enableLight[q]);
    70. EditorPrefs.SetFloat(kEditorPrefsName + ".color.r" + q, colorLight[q].r);
    71. EditorPrefs.SetFloat(kEditorPrefsName + ".color.g" + q, colorLight[q].g);
    72. EditorPrefs.SetFloat(kEditorPrefsName + ".color.b" + q, colorLight[q].b);
    73. EditorPrefs.SetFloat(kEditorPrefsName + ".color.a" + q, colorLight[q].a);
    74. EditorPrefs.SetFloat(kEditorPrefsName + ".dir.x" + q, dirLight[q].x);
    75. EditorPrefs.SetFloat(kEditorPrefsName + ".dir.y" + q, dirLight[q].y);
    76.  }
    77.  }
    78. }
    79.  
    80. classBakeMaterialextendsEditorWindow
    81. {
    82. privatestaticvarkMateriBakeNodeName = "__MateriaBakeSetup";
    83. privatestaticvarkWindowMinSize = Vector2 (300, 386);
    84.  
    85. privatestaticvarsettings : BakeMaterialSettings;
    86. privatestaticvarvisible : boolean = false;
    87.  
    88. privatevarcamera : GameObject;
    89. privatevarplane : GameObject;
    90. privatevarpreviewTexture : Texture;
    91. privatevarlights : GameObject[] = newGameObject[BakeMaterialSettings.kLights];
    92. privatevarstateChanged = false;
    93.  
    94. privatevartexViewScrollPosition = Vector2.zero;
    95. privatevarlastMaterial : Material;
    96.  
    97. privatevaroriginalScene = "";
    98.  
    99. privatevarscheduleBakeOnNextUpdate = false;
    100.  
    101.  
    102. privatefunctionSetupScene ()
    103.  {
    104. DestroyScene ();
    105. varoldGo = GameObject.Find(kMateriBakeNodeName);
    106. if (oldGo)
    107. DestroyImmediate (oldGo);
    108. camera = newGameObject (kMateriBakeNodeName, Camera);
    109. plane = GameObject.CreatePrimitive (PrimitiveType.Plane);
    110.  
    111. varcam = camera;
    112. cam.camera.backgroundColor = Color.black;
    113. cam.camera.clearFlags = CameraClearFlags.SolidColor;
    114. cam.camera.orthographic = true;
    115. cam.camera.orthographicSize = 5.0;
    116. cam.camera.cullingMask = 1 << settings.kBakingLayerShouldBeUnusedInScene;
    117.  
    118. plane.transform.parent = cam.transform;
    119. plane.transform.position = Vector3.forward * 10.0;
    120. plane.transform.rotation = Quaternion.Euler (0, 0, 180) * Quaternion.Euler (-90, 0, 0);
    121. plane.layer = settings.kBakingLayerShouldBeUnusedInScene;
    122.  
    123. for (varlinlights)
    124.  {
    125. l = newGameObject ("Light", Light);
    126. l.light.type = LightType.Directional;
    127. l.light.cullingMask = 1 << settings.kBakingLayerShouldBeUnusedInScene;
    128. l.transform.parent = cam.transform;
    129. l.SetActive(false);
    130.  }
    131.  }
    132.  
    133. privatefunctionUpdateScene (m : Material)
    134.  {
    135. for (q = 0; q < settings.kLights; ++q)
    136.  {
    137. lights[q].SetActive(settings.useCustomLights && settings.enableLight[q]);
    138. lights[q].light.color = settings.colorLight[q];
    139. lights[q].transform.rotation =
    140. Quaternion.AngleAxis(settings.dirLight[q].x, Vector3.up) *
    141. Quaternion.AngleAxis(settings.dirLight[q].y, Vector3.right);
    142.  }
    143.  
    144. if (settings.useCustomLights)
    145. RenderSettings.ambientLight = settings.ambient;
    146. elseif (settings.emptyScene)
    147. RenderSettings.ambientLight = Color.white;
    148.  
    149. plane.renderer.material = m;
    150.  }
    151.  
    152. privatefunctionDestroyScene ()
    153.  {
    154. GameObject.DestroyImmediate (camera);
    155. GameObject.DestroyImmediate (plane);
    156. GameObject.DestroyImmediate (previewTexture);
    157.  }
    158.  
    159. functionUpdateMaterialPreview (m : Material) : RenderTexture
    160.  {
    161. if (!m)
    162. return;
    163.  
    164. varsaveAmbientLight = RenderSettings.ambientLight;
    165. varsaveMainTexture = m.mainTexture;
    166. if (settings.bakeMainTexAsWhite)
    167. m.mainTexture = null;
    168.  
    169.  
    170. //setup
    171. if (!camera)
    172. SetupScene ();
    173. camera.SetActive(true);
    174. UpdateScene (m);
    175.  
    176. varres = FindLargestTextureResolution (plane.renderer.sharedMaterial, settings.minTextureResolution, settings.maxTextureResolution);
    177. varrt = RenderCameraToRenderTexture (camera.camera, res.x, res.y);
    178.  
    179. //restore
    180. camera.SetActive(false);
    181. RenderSettings.ambientLight = saveAmbientLight;
    182. m.mainTexture = saveMainTexture;
    183.  
    184. previewTexture = rt;
    185. returnrt;
    186.  }
    187.  
    188. functionCaptureMaterial(m : Material)
    189.  {
    190. varmatAssetPath = AssetDatabase.GetAssetPath (m);
    191. varassetPath = System.IO.Path.Combine (System.IO.Path.GetDirectoryName (matAssetPath), System.IO.Path.GetFileNameWithoutExtension (matAssetPath));
    192.  
    193. varrt = UpdateMaterialPreview (m);
    194. RenderTextureToPNG (rt, settings.bakeAlpha, assetPath + ".png");
    195.  }
    196.  
    197. functionOnEnable ()
    198.  {
    199. if (!settings)
    200. settings = newBakeMaterialSettings ();
    201. SetupScene ();
    202. visible = true;
    203.  }
    204.  
    205. functionOnDisable ()
    206.  {
    207. DestroyScene ();
    208. settings.Save ();
    209. visible = false;
    210.  }
    211.  
    212. staticfunctionGetTargetMaterial () : Material
    213.  {
    214. returnEditorUtility.InstanceIDToObject (Selection.activeInstanceID) asMaterial;
    215.  }
    216.  
    217. functionOnSelectionChange ()
    218.  {
    219. Repaint ();
    220.  }
    221.  
    222. functionUpdate ()
    223.  {
    224. varrebuildScene = false;
    225. if (scheduleBakeOnNextUpdate)
    226.  {
    227. Bake ();
    228. scheduleBakeOnNextUpdate = false;
    229. rebuildScene = true;
    230.  }
    231.  
    232. if (originalScene == "" && EditorApplication.currentScene == "")
    233. settings.emptyScene = true;
    234.  
    235. if (settings.emptyScene && originalScene == "" && EditorApplication.currentScene != "")
    236.  {
    237. DestroyScene ();
    238. if (EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    239.  {
    240. originalScene = EditorApplication.currentScene;
    241. EditorApplication.NewScene ();
    242.  }
    243. else
    244. settings.emptyScene = false;
    245. rebuildScene = true;
    246.  }
    247. elseif (!settings.emptyScene && originalScene != "")
    248.  {
    249. EditorApplication.OpenScene (originalScene);
    250. rebuildScene = true;
    251. originalScene = "";
    252.  }
    253.  
    254. if (rebuildScene)
    255.  {
    256. SetupScene ();
    257.  }
    258.  
    259. if (rebuildScene || stateChanged || !settings.emptyScene)
    260.  {
    261. UpdateMaterialPreview (lastMaterial);
    262. Repaint ();
    263. stateChanged = false;
    264.  }
    265.  }
    266.  
    267. functionOnGUI ()
    268.  {
    269. varmaterial = GetTargetMaterial ();
    270. if (lastMaterial != material)
    271. UpdateMaterialPreview (material);
    272. if (material)
    273. lastMaterial = material;
    274.  
    275. EditorGUILayout.BeginHorizontal();
    276. EditorGUILayout.BeginVertical(GUILayout.MaxWidth(200));
    277. if (!(originalScene == "" && EditorApplication.currentScene == ""))
    278.  {
    279. settings.emptyScene = !EditorGUILayout.BeginToggleGroup("Sceneligthing", !settings.emptyScene);
    280. EditorGUILayout.EndToggleGroup();
    281.  }
    282. settings.useCustomLights = EditorGUILayout.BeginToggleGroup("Customlighting", settings.useCustomLights);
    283. if (settings.useCustomLights)
    284.  {
    285. EditorGUI.indentLevel = 1;
    286. settings.ambient = EditorGUILayout.ColorField("Ambient", settings.ambient);
    287. for (varq = 0; q < settings.kLights; ++q)
    288.  {
    289. settings.enableLight[q] = EditorGUILayout.BeginToggleGroup("Light", settings.enableLight[q]);
    290. EditorGUI.indentLevel = 2;
    291. settings.colorLight[q] = EditorGUILayout.ColorField("Color", settings.colorLight[q]);
    292. settings.dirLight[q] = EditorGUILayout.Vector2Field("Direction", settings.dirLight[q]);
    293. EditorGUILayout.EndToggleGroup();
    294.  }
    295.  }
    296. EditorGUI.indentLevel = 0;
    297. EditorGUILayout.EndToggleGroup();
    298.  
    299. settings.bakeAlpha = EditorGUILayout.Toggle("BakeAlpha", settings.bakeAlpha);
    300. settings.bakeMainTexAsWhite = !EditorGUILayout.Toggle("MainTex", !settings.bakeMainTexAsWhite);
    301. settings.minTextureResolution = EditorGUILayout.IntField("MinResolution", settings.minTextureResolution);
    302. settings.maxTextureResolution = EditorGUILayout.IntField("MaxResolution", settings.maxTextureResolution);
    303. settings.minTextureResolution = Mathf.Max(2, settings.minTextureResolution);
    304. settings.maxTextureResolution = Mathf.Max(settings.minTextureResolution, settings.maxTextureResolution);
    305.  
    306. EditorGUILayout.BeginHorizontal();
    307. if (GUILayout.Button("Bake"))
    308.  {
    309. CaptureMaterial (lastMaterial);
    310.  }
    311. if (GUILayout.Button("BakeSelected"))
    312.  {
    313. scheduleBakeOnNextUpdate = true;
    314.  }
    315. EditorGUILayout.EndHorizontal();
    316.  
    317. EditorGUILayout.EndVertical();
    318.  
    319. texViewScrollPosition = EditorGUILayout.BeginScrollView (texViewScrollPosition);
    320. varr = GUILayoutUtility.GetAspectRect(1.0f);
    321. if (previewTexture)
    322. EditorGUI.DrawPreviewTexture(r, previewTexture);
    323. EditorGUILayout.EndScrollView();
    324. EditorGUILayout.EndHorizontal();
    325.  
    326. if (GUI.changed)
    327.  {
    328. stateChanged = true;
    329.  }
    330.  }
    331.  
    332. @MenuItem("Custom/BakeMaterial ...", false, 5)
    333. staticfunctionCreateBakeEditor()
    334.  {
    335. varwindow = EditorWindow.GetWindow(BakeMaterial);
    336. window.title = "BakeMaterial";
    337. window.minSize = kWindowMinSize;
    338. window.Show();
    339.  }
    340.  
    341. @MenuItem("Custom/BakeSelectedMaterials", false, 4)
    342. staticfunctionBake()
    343.  {
    344. varinstanceIDs = Selection.instanceIDs;
    345. varcurrentScene = EditorApplication.currentScene;
    346.  
    347. varwasAlreadyVisible = BakeMaterial.visible;
    348. varwindow = EditorWindow.GetWindow(BakeMaterial);
    349.  
    350. if (window.settings.emptyScene)
    351.  {
    352. if (!EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    353. return;
    354. EditorApplication.NewScene ();
    355.  }
    356.  
    357. window.SetupScene ();
    358. for (variininstanceIDs)
    359.  {
    360. varm : Material = EditorUtility.InstanceIDToObject (i) asMaterial;
    361. if (m)
    362. window.CaptureMaterial (m);
    363.  }
    364. window.DestroyScene ();
    365.  
    366. if (window.settings.emptyScene && currentScene)
    367.  {
    368. EditorApplication.OpenScene (currentScene);
    369.  }
    370.  
    371. if (!wasAlreadyVisible)
    372. window.Close ();
    373.  }
    374.  
    375. staticfunctionFindLargestTextureResolution (m : Material, minTexRes : int, maxTexRes : int) : Vector2
    376.  {
    377. varres = Vector2 (minTexRes, minTexRes);
    378. for (varninBakeMaterialSettings.kStandardTexNames)
    379.  {
    380. if (!m.HasProperty (n))
    381. continue;
    382.  
    383. vart : Texture = m.GetTexture (n);
    384. if (!t)
    385. continue;
    386.  
    387. res.x = Mathf.Max (res.x, t.width);
    388. res.y = Mathf.Max (res.y, t.height);
    389.  }
    390. res.x = Mathf.Min (res.x, maxTexRes);
    391. res.y = Mathf.Min (res.y, maxTexRes);
    392. returnres;
    393.  }
    394.  
    395. staticfunctionRenderCameraToRenderTexture (cam : Camera, width : int, height : int) : RenderTexture
    396.  {
    397. varrt = cam.camera.targetTexture;
    398. if (rt && rt.width != width && rt.height != height)
    399. DestroyImmediate(rt);
    400. if (!rt)
    401. rt = newRenderTexture (width, height, 24);
    402. cam.camera.targetTexture = rt;
    403. cam.camera.Render ();
    404. returnrt;
    405.  }
    406.  
    407. staticfunctionRenderTextureToPNG (rt : RenderTexture, bakeAlpha : boolean, assetPath : String)
    408.  {
    409. RenderTexture.active = rt;
    410.  
    411. varscreenShot = newTexture2D (rt.width, rt.height, bakeAlpha? TextureFormat.ARGB32 : TextureFormat.RGB24, false);
    412. screenShot.ReadPixels (Rect (0, 0, rt.width, rt.height), 0, 0);
    413.  
    414. RenderTexture.active = null;
    415.  
    416. varbytes = screenShot.EncodeToPNG ();
    417. System.IO.File.WriteAllBytes (assetPath, bytes);
    418.  
    419. AssetDatabase.ImportAsset (assetPath, ImportAssetOptions.ForceUpdate);
    420.  }
    421. }
    422.  
    423.  
     
  6. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    882
    i have copy the script

    and i got


    i don't reconize 'DestroyImmediate' it's maybie js ?
    Unknown identifier: 'BakeMaterial'.

    he want string for reference
    Ambiguous reference 'HasProperty': UnityEngine.Material.HasProperty(int), UnityEngine.Material.HasProperty(String)

    like copy past here work not realy well i have maybie a misstake somewhere
     
  7. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    882
    ok i have fix one next time don't attack brain like this at Monday morning lol



    i have settings' is not a member of 'UnityEditor.EditorWindow'.
    maybie because is one
    var window = EditorWindow.GetWindow(BakeMaterial);
    so i replace window by BakeMaterial is look work i will try
     
  8. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    882
    forget what's have say he say BakeMaterial' is required to access non static member 'SetupScene'.
     
  9. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    882
    please !<:) want see that's in action
     
  10. AndersonVieira

    AndersonVieira

    Joined:
    Sep 26, 2014
    Posts:
    1
    AM NEW IN UNITY, ME TEACH SOMEONE TO INSTALL THIS SCRIPT?
     
  11. Kay20000

    Kay20000

    Joined:
    May 8, 2013
    Posts:
    8
    This works with Version 4.5.5f1

    Save it in 'Editor' folder.
    Then select Material and Menu>Bake Selected Material

    Code (JavaScript):
    1. #pragma strict
    2. class BakeMaterialSettings
    3. {
    4. private static var kEditorPrefsName = "BakeMaterialSettings";
    5. static var kBakingLayerShouldBeUnusedInScene = 30;
    6. static var kStandardTexNames = new Array ("_MainTex", "_BumpMap", "_Detail", "_ParallaxMap","_Parallax");
    7. var bakeAlpha = false;
    8. var bakeMainTexAsWhite = false;
    9. var minTextureResolution = 8;
    10. var maxTextureResolution = 2048;
    11. var emptyScene = false;
    12. var useCustomLights = false;
    13. var ambient = Color.black;
    14. static var kLights = 3;
    15. var enableLight = new boolean[kLights];
    16. var colorLight = new Color[kLights];
    17. var dirLight = new Vector2[kLights];
    18. function BakeMaterialSettings ()
    19. {
    20. Load ();
    21. }
    22. function Load ()
    23. {
    24. bakeAlpha = EditorPrefs.GetBool(kEditorPrefsName + ".bakeAlpha");
    25. bakeMainTexAsWhite = EditorPrefs.GetBool(kEditorPrefsName + ".bakeMainTexAsWhite");
    26. minTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".minTextureResolution", 8);
    27. maxTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".maxTextureResolution", 2048);
    28. emptyScene = EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene");
    29. useCustomLights = EditorPrefs.GetBool(kEditorPrefsName + ".useCustomLights");
    30. ambient.r = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.r");
    31. ambient.g = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.g");
    32. ambient.b = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.b");
    33. ambient.a = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.a", 1.0f);
    34. for (var q = 0; q < kLights; ++q)
    35. {
    36. enableLight[q] = EditorPrefs.GetBool(kEditorPrefsName + ".enableLight" + q);
    37. colorLight[q].r = EditorPrefs.GetFloat(kEditorPrefsName + ".color.r" + q, 0.5f);
    38. colorLight[q].g = EditorPrefs.GetFloat(kEditorPrefsName + ".color.g" + q, 0.5f);
    39. colorLight[q].b = EditorPrefs.GetFloat(kEditorPrefsName + ".color.b" + q, 0.5f);
    40. colorLight[q].a = EditorPrefs.GetFloat(kEditorPrefsName + ".color.a" + q, 1.0f);
    41. dirLight[q].x = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.x" + q);
    42. dirLight[q].y = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.y" + q);
    43. }
    44. }
    45. function Save ()
    46. {
    47. EditorPrefs.SetBool(kEditorPrefsName + ".bakeAlpha", bakeAlpha);
    48. EditorPrefs.SetBool(kEditorPrefsName + ".bakeMainTexAsWhite", bakeMainTexAsWhite);
    49. EditorPrefs.SetInt(kEditorPrefsName + ".minTextureResolution", minTextureResolution);
    50. EditorPrefs.SetInt(kEditorPrefsName + ".maxTextureResolution", maxTextureResolution);
    51. EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene", emptyScene);
    52. EditorPrefs.SetBool(kEditorPrefsName + ".useCustomLights", useCustomLights);
    53. EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.r", ambient.r);
    54. EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.g", ambient.g);
    55. EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.b", ambient.b);
    56. EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.a", ambient.a);
    57. for (var q = 0; q < kLights; ++q)
    58. {
    59. EditorPrefs.SetBool(kEditorPrefsName + ".enableLight" + q, enableLight[q]);
    60. EditorPrefs.SetFloat(kEditorPrefsName + ".color.r" + q, colorLight[q].r);
    61. EditorPrefs.SetFloat(kEditorPrefsName + ".color.g" + q, colorLight[q].g);
    62. EditorPrefs.SetFloat(kEditorPrefsName + ".color.b" + q, colorLight[q].b);
    63. EditorPrefs.SetFloat(kEditorPrefsName + ".color.a" + q, colorLight[q].a);
    64. EditorPrefs.SetFloat(kEditorPrefsName + ".dir.x" + q, dirLight[q].x);
    65. EditorPrefs.SetFloat(kEditorPrefsName + ".dir.y" + q, dirLight[q].y);
    66. }
    67. }
    68. }
    69. class BakeMaterial extends EditorWindow
    70. {
    71. private static var kMateriBakeNodeName = "__MateriaBakeSetup";
    72. private static var kWindowMinSize = Vector2 (300, 386);
    73. private static var settings : BakeMaterialSettings;
    74. private static var visible : boolean = false;
    75. private var camera : GameObject;
    76. private var plane : GameObject;
    77. private var previewTexture : Texture;
    78. private var lights : GameObject[] = new GameObject[BakeMaterialSettings.kLights];
    79. private var stateChanged = false;
    80. private var texViewScrollPosition = Vector2.zero;
    81. private var lastMaterial : Material;
    82. private var originalScene = "";
    83. private var scheduleBakeOnNextUpdate = false;
    84. private function SetupScene ()
    85. {
    86. DestroyScene ();
    87. var oldGo = GameObject.Find(kMateriBakeNodeName);
    88. if (oldGo)
    89. DestroyImmediate (oldGo);
    90. camera = new GameObject (kMateriBakeNodeName, Camera);
    91. plane = GameObject.CreatePrimitive (PrimitiveType.Plane);
    92. var cam = camera;
    93. cam.camera.backgroundColor = Color.black;
    94. cam.camera.clearFlags = CameraClearFlags.SolidColor;
    95. cam.camera.orthographic = true;
    96. cam.camera.orthographicSize = 5.0;
    97. cam.camera.cullingMask = 1 << settings.kBakingLayerShouldBeUnusedInScene;
    98. plane.transform.parent = cam.transform;
    99. plane.transform.position = Vector3.forward * 10.0;
    100. plane.transform.rotation = Quaternion.Euler (0, 0, 180) * Quaternion.Euler (-90, 0, 0);
    101. plane.layer = settings.kBakingLayerShouldBeUnusedInScene;
    102. for (var l in lights)
    103. {
    104. l = new GameObject ("Light", Light);
    105. l.light.type = LightType.Directional;
    106. l.light.cullingMask = 1 << settings.kBakingLayerShouldBeUnusedInScene;
    107. l.transform.parent = cam.transform;
    108. l.SetActive(false);
    109. }
    110. }
    111. private function UpdateScene (m : Material)
    112. {
    113. for (var q = 0; q < settings.kLights; ++q)
    114. {
    115. lights[q].SetActive(settings.useCustomLights && settings.enableLight[q]);
    116. lights[q].light.color = settings.colorLight[q];
    117. lights[q].transform.rotation =
    118. Quaternion.AngleAxis(settings.dirLight[q].x, Vector3.up) *
    119. Quaternion.AngleAxis(settings.dirLight[q].y, Vector3.right);
    120. }
    121. if (settings.useCustomLights)
    122. RenderSettings.ambientLight = settings.ambient;
    123. else if  (settings.emptyScene)
    124. RenderSettings.ambientLight = Color.white;
    125. plane.renderer.material = m;
    126. }
    127. private function DestroyScene ()
    128. {
    129. GameObject.DestroyImmediate (camera);
    130. GameObject.DestroyImmediate (plane);
    131. GameObject.DestroyImmediate (previewTexture);
    132. }
    133. function UpdateMaterialPreview (m : Material) : RenderTexture
    134. {
    135. if (!m)
    136. return;
    137. var saveAmbientLight = RenderSettings.ambientLight;
    138. var saveMainTexture = m.mainTexture;
    139. if (settings.bakeMainTexAsWhite)
    140. m.mainTexture = null;
    141. //setup
    142. if (!camera)
    143. SetupScene ();
    144. camera.SetActive(true);
    145. UpdateScene (m);
    146. var res = FindLargestTextureResolution (plane.renderer.sharedMaterial, settings.minTextureResolution, settings.maxTextureResolution);
    147. var rt = RenderCameraToRenderTexture (camera.camera, res.x, res.y);
    148. //restore
    149. camera.SetActive(false);
    150. RenderSettings.ambientLight = saveAmbientLight;
    151. m.mainTexture = saveMainTexture;
    152. previewTexture = rt;
    153. return rt;
    154. }
    155. function CaptureMaterial(m : Material)
    156. {
    157. var matAssetPath = AssetDatabase.GetAssetPath (m);
    158. var assetPath = System.IO.Path.Combine (System.IO.Path.GetDirectoryName (matAssetPath), System.IO.Path.GetFileNameWithoutExtension (matAssetPath));
    159. var rt = UpdateMaterialPreview (m);
    160. RenderTextureToPNG (rt, settings.bakeAlpha, assetPath + ".png");
    161. }
    162. function OnEnable ()
    163. {
    164. if (!settings)
    165. settings = new BakeMaterialSettings ();
    166. SetupScene ();
    167. visible = true;
    168. }
    169. function OnDisable ()
    170. {
    171. DestroyScene ();
    172. settings.Save ();
    173. visible = false;
    174. }
    175. static function GetTargetMaterial () : Material
    176. {
    177. return EditorUtility.InstanceIDToObject (Selection.activeInstanceID) as Material;
    178. }
    179. function OnSelectionChange ()
    180. {
    181. Repaint ();
    182. }
    183. function [URL='http://forum.unity3d.com/#'][U][B]Update[U][B][IMG]http://cdncache-a.akamaihd.net/items/it/img/arrow-10x10.png[/IMG][/B][/U][/B][/U][/URL] ()
    184. {
    185. var rebuildScene = false;
    186. if (scheduleBakeOnNextUpdate)
    187. {
    188. Bake ();
    189. scheduleBakeOnNextUpdate = false;
    190. rebuildScene = true;
    191. }
    192. if (originalScene == "" && EditorApplication.currentScene == "")
    193. settings.emptyScene = true;
    194. if (settings.emptyScene && originalScene == "" && EditorApplication.currentScene != "")
    195. {
    196. DestroyScene ();
    197. if (EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    198. {
    199. originalScene = EditorApplication.currentScene;
    200. EditorApplication.NewScene ();
    201. }
    202. else
    203. settings.emptyScene = false;
    204. rebuildScene = true;
    205. }
    206. else if (!settings.emptyScene && originalScene != "")
    207. {
    208. EditorApplication.OpenScene (originalScene);
    209. rebuildScene = true;
    210. originalScene = "";
    211. }
    212. if (rebuildScene)
    213. {
    214. SetupScene ();
    215. }
    216. if (rebuildScene || stateChanged || !settings.emptyScene)
    217. {
    218. UpdateMaterialPreview (lastMaterial);
    219. Repaint ();
    220. stateChanged = false;
    221. }
    222. }
    223. function OnGUI ()
    224. {
    225. var material = GetTargetMaterial ();
    226. if (lastMaterial != material)
    227. UpdateMaterialPreview (material);
    228. if (material)
    229. lastMaterial = material;
    230. EditorGUILayout.BeginHorizontal();
    231. EditorGUILayout.BeginVertical(GUILayout.MaxWidth(200));
    232. if (!(originalScene == "" && EditorApplication.currentScene == ""))
    233. {
    234. settings.emptyScene = !EditorGUILayout.BeginToggleGroup("Sceneligthing", !settings.emptyScene);
    235. EditorGUILayout.EndToggleGroup();
    236. }
    237. settings.useCustomLights = EditorGUILayout.BeginToggleGroup("Customlighting", settings.useCustomLights);
    238. if (settings.useCustomLights)
    239. {
    240. EditorGUI.indentLevel = 1;
    241. settings.ambient = EditorGUILayout.ColorField("Ambient", settings.ambient);
    242. for (var q = 0; q < settings.kLights; ++q)
    243. {
    244. settings.enableLight[q] = EditorGUILayout.BeginToggleGroup("Light", settings.enableLight[q]);
    245. EditorGUI.indentLevel = 2;
    246. settings.colorLight[q] = EditorGUILayout.ColorField("Color", settings.colorLight[q]);
    247. settings.dirLight[q] = EditorGUILayout.Vector2Field("Direction", settings.dirLight[q]);
    248. EditorGUILayout.EndToggleGroup();
    249. }
    250. }
    251. EditorGUI.indentLevel = 0;
    252. EditorGUILayout.EndToggleGroup();
    253. settings.bakeAlpha = EditorGUILayout.Toggle("BakeAlpha", settings.bakeAlpha);
    254. settings.bakeMainTexAsWhite = !EditorGUILayout.Toggle("MainTex", !settings.bakeMainTexAsWhite);
    255. settings.minTextureResolution = EditorGUILayout.IntField("MinResolution", settings.minTextureResolution);
    256. settings.maxTextureResolution = EditorGUILayout.IntField("MaxResolution", settings.maxTextureResolution);
    257. settings.minTextureResolution = Mathf.Max(2, settings.minTextureResolution);
    258. settings.maxTextureResolution = Mathf.Max(settings.minTextureResolution, settings.maxTextureResolution);
    259. EditorGUILayout.BeginHorizontal();
    260. if (GUILayout.Button("Bake"))
    261. {
    262. CaptureMaterial (lastMaterial);
    263. }
    264. if (GUILayout.Button("BakeSelected"))
    265. {
    266. scheduleBakeOnNextUpdate = true;
    267. }
    268. EditorGUILayout.EndHorizontal();
    269. EditorGUILayout.EndVertical();
    270. texViewScrollPosition = EditorGUILayout.BeginScrollView (texViewScrollPosition);
    271. var r = GUILayoutUtility.GetAspectRect(1.0f);
    272. if (previewTexture)
    273. EditorGUI.DrawPreviewTexture(r, previewTexture);
    274. EditorGUILayout.EndScrollView();
    275. EditorGUILayout.EndHorizontal();
    276. if (GUI.changed)
    277. {
    278. stateChanged = true;
    279. }
    280. }
    281. @MenuItem("Custom/BakeMaterial ...", false, 5)
    282. static function CreateBakeEditor()
    283. {
    284. var window = EditorWindow.GetWindow(BakeMaterial);
    285. window.title = "BakeMaterial";
    286. window.minSize = kWindowMinSize;
    287. window.Show();
    288. }
    289. @MenuItem("Custom/BakeSelectedMaterials", false, 4)
    290. static function Bake()
    291. {
    292. var instanceIDs = Selection.instanceIDs;
    293. var currentScene = EditorApplication.currentScene;
    294. var wasAlreadyVisible = BakeMaterial.visible;
    295. var window :BakeMaterial = EditorWindow.GetWindow(BakeMaterial);
    296. if (window.settings.emptyScene)
    297. {
    298. if (!EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    299. return;
    300. EditorApplication.NewScene ();
    301. }
    302. window.SetupScene ();
    303. for (var i in instanceIDs)
    304. {
    305. var m : Material = EditorUtility.InstanceIDToObject (i) as Material;
    306. if (m)
    307. window.CaptureMaterial (m);
    308. }
    309. window.DestroyScene ();
    310. if (window.settings.emptyScene && currentScene)
    311. {
    312. EditorApplication.OpenScene (currentScene);
    313. }
    314. if (!wasAlreadyVisible)
    315. window.Close ();
    316. }
    317. static function FindLargestTextureResolution (m : Material, minTexRes : int, maxTexRes : int) : Vector2
    318. {
    319. var res = Vector2 (minTexRes, minTexRes);
    320.  
    321. for (var n :String in BakeMaterialSettings.kStandardTexNames)
    322. {
    323. var t : Texture;
    324. Debug.Log("try get"+n);
    325. Debug.Log("has"+m.HasProperty (n));
    326. if (m.HasProperty (n)){
    327. t  = m.GetTexture (n);
    328. }
    329. if (t==null)continue;
    330. res.x = Mathf.Max (res.x, t.width);
    331. res.y = Mathf.Max (res.y, t.height);
    332. }
    333. res.x = Mathf.Min (res.x, maxTexRes);
    334. res.y = Mathf.Min (res.y, maxTexRes);
    335. return res;
    336. }
    337. static function RenderCameraToRenderTexture (cam : Camera, width : int, height : int) : RenderTexture
    338. {
    339. var rt = cam.camera.targetTexture;
    340. if (rt && rt.width != width && rt.height != height)
    341. DestroyImmediate(rt);
    342. if (!rt)
    343. rt = new RenderTexture (width, height, 24);
    344. cam.camera.targetTexture = rt;
    345. cam.camera.Render ();
    346. return rt;
    347. }
    348. static function RenderTextureToPNG (rt : RenderTexture, bakeAlpha : boolean, assetPath : String)
    349. {
    350. RenderTexture.active = rt;
    351. var screenShot = new Texture2D (rt.width, rt.height, bakeAlpha? TextureFormat.ARGB32 : TextureFormat.RGB24, false);
    352. screenShot.ReadPixels (Rect (0, 0, rt.width, rt.height), 0, 0);
    353. RenderTexture.active = null;
    354. var bytes = screenShot.EncodeToPNG ();
    355. System.IO.File.WriteAllBytes (assetPath, bytes);
    356. AssetDatabase.ImportAsset (assetPath, ImportAssetOptions.ForceUpdate);
    357. }
    358. }
    359.  
     
  12. blamejane

    blamejane

    Joined:
    Jul 8, 2013
    Posts:
    228
    Just curious if anyone has gotten this script to work with 4.6? When I run the script on selected material, the script generates a bake texture (png) however it only bakes about 1/4 of the texture and then stops.
     
  13. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    882
    not working in 4.6 got error compile but always interest by solution for baking
     
  14. blamejane

    blamejane

    Joined:
    Jul 8, 2013
    Posts:
    228
    Thanks for checking. Were you able to generate any kind of texture, even partial?

    After selecting the material and then clicking the menu Custom -> Bake Material, I am presented with he settings dialog. From here I check Scene lighting and click Bake. This will generate the partially complete png, placing it into the same folder as the material.

    I'm using the free version of Unity 4.6.2 f1
     
  15. terraformer2015

    terraformer2015

    Joined:
    Jul 1, 2015
    Posts:
    1
    Anybody have this working for unity 5? Would be much appreciated!
     
  16. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    882
    need please too mutch interessing
     
    Mihai77 likes this.
  17. Vashchuk

    Vashchuk

    Joined:
    May 24, 2012
    Posts:
    25
    Works fine with Unity 5.2

    Code (JavaScript):
    1. /*
    2.     Instructions:
    3.     1.Select material to bake
    4.     2.Go Custom/Bake Material...
    5. */
    6. class BakeMaterialSettings
    7. {
    8.     private static var kEditorPrefsName = "BakeMaterialSettings";
    9.     static var kBakingLayerShouldBeUnusedInScene = 30;
    10.     static var kStandardTexNames = new Array ("_MainTex", "_BumpMap", "_Detail", "_ParallaxMap", "_Parallax");
    11.     var bakeAlpha = false;
    12.     var bakeMainTexAsWhite = false;
    13.     var minTextureResolution = 8;
    14.     var maxTextureResolution = 2048;
    15.     var emptyScene = false;
    16.     var useCustomLights = false;
    17.     var ambient = Color.black;
    18.     static var kLights = 3;
    19.     var enableLight = new boolean[kLights];
    20.     var colorLight = new Color[kLights];
    21.     var dirLight = new Vector2[kLights];
    22.     function BakeMaterialSettings ()
    23.     {
    24.         Load ();
    25.     }
    26.     function Load ()
    27.     {
    28.         bakeAlpha = EditorPrefs.GetBool(kEditorPrefsName + ".bakeAlpha");
    29.         bakeMainTexAsWhite = EditorPrefs.GetBool(kEditorPrefsName + ".bakeMainTexAsWhite");
    30.         minTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".minTextureResolution", 8);
    31.         maxTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".maxTextureResolution", 2048);
    32.         emptyScene = EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene");
    33.         useCustomLights = EditorPrefs.GetBool(kEditorPrefsName + ".useCustomLights");
    34.         ambient.r = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.r");
    35.         ambient.g = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.g");
    36.         ambient.b = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.b");
    37.         ambient.a = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.a", 1.0f);
    38.         for (var q = 0; q < kLights; ++q)
    39.         {
    40.             enableLight[q] = EditorPrefs.GetBool(kEditorPrefsName + ".enableLight" + q);
    41.             colorLight[q].r = EditorPrefs.GetFloat(kEditorPrefsName + ".color.r" + q, 0.5f);
    42.             colorLight[q].g = EditorPrefs.GetFloat(kEditorPrefsName + ".color.g" + q, 0.5f);
    43.             colorLight[q].b = EditorPrefs.GetFloat(kEditorPrefsName + ".color.b" + q, 0.5f);
    44.             colorLight[q].a = EditorPrefs.GetFloat(kEditorPrefsName + ".color.a" + q, 1.0f);
    45.             dirLight[q].x = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.x" + q);
    46.             dirLight[q].y = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.y" + q);
    47.         }
    48.     }
    49.     function Save ()
    50.     {
    51.         EditorPrefs.SetBool(kEditorPrefsName + ".bakeAlpha", bakeAlpha);
    52.         EditorPrefs.SetBool(kEditorPrefsName + ".bakeMainTexAsWhite", bakeMainTexAsWhite);
    53.         EditorPrefs.SetInt(kEditorPrefsName + ".minTextureResolution", minTextureResolution);
    54.         EditorPrefs.SetInt(kEditorPrefsName + ".maxTextureResolution", maxTextureResolution);
    55.         EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene", emptyScene);
    56.         EditorPrefs.SetBool(kEditorPrefsName + ".useCustomLights", useCustomLights);
    57.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.r", ambient.r);
    58.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.g", ambient.g);
    59.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.b", ambient.b);
    60.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.a", ambient.a);
    61.         for (var q = 0; q < kLights; ++q)
    62.         {
    63.             EditorPrefs.SetBool(kEditorPrefsName + ".enableLight" + q, enableLight[q]);
    64.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.r" + q, colorLight[q].r);
    65.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.g" + q, colorLight[q].g);
    66.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.b" + q, colorLight[q].b);
    67.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.a" + q, colorLight[q].a);
    68.             EditorPrefs.SetFloat(kEditorPrefsName + ".dir.x" + q, dirLight[q].x);
    69.             EditorPrefs.SetFloat(kEditorPrefsName + ".dir.y" + q, dirLight[q].y);
    70.         }
    71.     }
    72. }
    73. class BakeMaterial extends EditorWindow
    74. {
    75.     private static var kMateriBakeNodeName = "__MateriaBakeSetup";
    76.     private static var kWindowMinSize = Vector2 (300, 386);
    77.     private static var settings : BakeMaterialSettings;
    78.     private static var visible : boolean = false;
    79.     private var camera : GameObject;
    80.     private var plane : GameObject;
    81.     private var previewTexture : Texture;
    82.     private var lights : GameObject[] = new GameObject[BakeMaterialSettings.kLights];
    83.     private var stateChanged = false;
    84.     private var texViewScrollPosition = Vector2.zero;
    85.     private var lastMaterial : Material;
    86.     private var originalScene = "";
    87.     private var scheduleBakeOnNextUpdate = false;
    88.     private function SetupScene ()
    89.     {
    90.         DestroyScene ();
    91.         var oldGo = GameObject.Find(kMateriBakeNodeName);
    92.         if (oldGo)
    93.             DestroyImmediate (oldGo);
    94.         camera = new GameObject (kMateriBakeNodeName, Camera);
    95.         plane = GameObject.CreatePrimitive (PrimitiveType.Plane);
    96.         var cam = camera;
    97.         cam.GetComponent.<Camera>().backgroundColor = Color.black;
    98.         cam.GetComponent.<Camera>().clearFlags = CameraClearFlags.SolidColor;
    99.         cam.GetComponent.<Camera>().orthographic = true;
    100.         cam.GetComponent.<Camera>().orthographicSize = 5.0;
    101.         cam.GetComponent.<Camera>().cullingMask = 1 << settings.kBakingLayerShouldBeUnusedInScene;
    102.         plane.transform.parent = cam.transform;
    103.         plane.transform.position = Vector3.forward * 10.0;
    104.         plane.transform.rotation = Quaternion.Euler (0, 0, 180) * Quaternion.Euler (-90, 0, 0);
    105.         plane.layer = settings.kBakingLayerShouldBeUnusedInScene;
    106.         for (var l in lights)
    107.         {
    108.             l = new GameObject ("Light", Light);
    109.             l.GetComponent.<Light>().type = LightType.Directional;
    110.             l.GetComponent.<Light>().cullingMask = 1 << settings.kBakingLayerShouldBeUnusedInScene;
    111.             l.transform.parent = cam.transform;
    112.             l.SetActive(false);
    113.         }
    114.     }
    115.     private function UpdateScene (m : Material)
    116.     {
    117.         for (q = 0; q < settings.kLights; ++q)
    118.         {
    119.             lights[q].SetActive(settings.useCustomLights && settings.enableLight[q]);
    120.             lights[q].GetComponent.<Light>().color = settings.colorLight[q];
    121.             lights[q].transform.rotation =
    122.                 Quaternion.AngleAxis(settings.dirLight[q].x, Vector3.up) *
    123.                 Quaternion.AngleAxis(settings.dirLight[q].y, Vector3.right);
    124.         }
    125.         if (settings.useCustomLights)
    126.             RenderSettings.ambientLight = settings.ambient;
    127.         else if (settings.emptyScene)
    128.             RenderSettings.ambientLight = Color.white;
    129.         plane.GetComponent.<Renderer>().material = m;
    130.     }
    131.     private function DestroyScene ()
    132.     {
    133.         GameObject.DestroyImmediate (camera);
    134.         GameObject.DestroyImmediate (plane);
    135.         GameObject.DestroyImmediate (previewTexture);
    136.     }
    137.     function UpdateMaterialPreview (m : Material) : RenderTexture
    138.     {
    139.         if (!m)
    140.             return;
    141.         var saveAmbientLight = RenderSettings.ambientLight;
    142.         var saveMainTexture = m.mainTexture;
    143.         if (settings.bakeMainTexAsWhite)
    144.             m.mainTexture = null;
    145.         // setup
    146.         if (!camera)
    147.             SetupScene ();
    148.         camera.SetActive(true);
    149.         UpdateScene (m);
    150.         var res = FindLargestTextureResolution (plane.GetComponent.<Renderer>().sharedMaterial, settings.minTextureResolution, settings.maxTextureResolution);
    151.         var rt = RenderCameraToRenderTexture (camera.GetComponent.<Camera>(), res.x, res.y);
    152.         // restore
    153.         camera.SetActive(false);
    154.         RenderSettings.ambientLight = saveAmbientLight;
    155.         m.mainTexture = saveMainTexture;
    156.         previewTexture = rt;
    157.         return rt;
    158.     }
    159.      function CaptureMaterial(m : Material)
    160.     {
    161.         var matAssetPath = AssetDatabase.GetAssetPath (m);
    162.         var assetPath = System.IO.Path.Combine (System.IO.Path.GetDirectoryName (matAssetPath), System.IO.Path.GetFileNameWithoutExtension (matAssetPath));
    163.         var rt = UpdateMaterialPreview (m);
    164.         RenderTextureToPNG (rt, settings.bakeAlpha, assetPath + ".png");
    165.     }
    166.     function OnEnable ()
    167.     {
    168.         if (!settings)
    169.             settings = new BakeMaterialSettings ();
    170.         SetupScene ();
    171.         visible = true;
    172.     }
    173.     function OnDisable ()
    174.     {
    175.         DestroyScene ();
    176.         settings.Save ();
    177.         visible = false;
    178.     }
    179.     static function GetTargetMaterial () : Material
    180.     {
    181.         return EditorUtility.InstanceIDToObject (Selection.activeInstanceID) as Material;
    182.     }
    183.     function OnSelectionChange ()
    184.     {
    185.         Repaint ();
    186.     }
    187.     function Update ()
    188.     {
    189.         var rebuildScene = false;
    190.         if (scheduleBakeOnNextUpdate)
    191.         {
    192.             Bake ();
    193.             scheduleBakeOnNextUpdate = false;
    194.             rebuildScene = true;
    195.         }
    196.         if (originalScene == "" && EditorApplication.currentScene == "")
    197.             settings.emptyScene = true;
    198.         if (settings.emptyScene && originalScene == "" && EditorApplication.currentScene != "")
    199.         {
    200.             DestroyScene ();
    201.             if (EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    202.             {
    203.                 originalScene = EditorApplication.currentScene;
    204.                 EditorApplication.NewScene ();
    205.             }
    206.             else
    207.                 settings.emptyScene = false;
    208.             rebuildScene = true;          
    209.         }
    210.         else if (!settings.emptyScene && originalScene != "")
    211.         {
    212.             EditorApplication.OpenScene (originalScene);
    213.             rebuildScene = true;
    214.             originalScene = "";
    215.         }
    216.         if (rebuildScene)
    217.         {
    218.             SetupScene ();
    219.         }
    220.         if (rebuildScene || stateChanged || !settings.emptyScene)
    221.         {
    222.             UpdateMaterialPreview (lastMaterial);
    223.             Repaint ();
    224.             stateChanged = false;
    225.         }
    226.     }
    227.     function OnGUI ()
    228.     {
    229.         var material = GetTargetMaterial ();
    230.         if (lastMaterial != material)
    231.             UpdateMaterialPreview (material);
    232.         if (material)
    233.             lastMaterial = material;
    234.         EditorGUILayout.BeginHorizontal();
    235.             EditorGUILayout.BeginVertical(GUILayout.MaxWidth(200));
    236.                 if (!(originalScene == "" && EditorApplication.currentScene == ""))
    237.                 {
    238.                     settings.emptyScene = !EditorGUILayout.BeginToggleGroup("Scene ligthing", !settings.emptyScene);
    239.                     EditorGUILayout.EndToggleGroup();
    240.                 }
    241.                 settings.useCustomLights = EditorGUILayout.BeginToggleGroup("Custom lighting", settings.useCustomLights);
    242.                 if (settings.useCustomLights)
    243.                 {
    244.                     EditorGUI.indentLevel = 1;
    245.                     settings.ambient = EditorGUILayout.ColorField("Ambient", settings.ambient);
    246.                     for (var q = 0; q < settings.kLights; ++q)
    247.                     {
    248.                         settings.enableLight[q] = EditorGUILayout.BeginToggleGroup("Light", settings.enableLight[q]);
    249.                         EditorGUI.indentLevel = 2;
    250.                             settings.colorLight[q] = EditorGUILayout.ColorField("Color", settings.colorLight[q]);
    251.                             settings.dirLight[q] = EditorGUILayout.Vector2Field("Direction", settings.dirLight[q]);
    252.                         EditorGUILayout.EndToggleGroup();
    253.                     }
    254.                 }
    255.                 EditorGUI.indentLevel = 0;
    256.                 EditorGUILayout.EndToggleGroup();
    257.                 settings.bakeAlpha = EditorGUILayout.Toggle("Bake Alpha", settings.bakeAlpha);
    258.                 settings.bakeMainTexAsWhite = !EditorGUILayout.Toggle("MainTex", !settings.bakeMainTexAsWhite);
    259.                 settings.minTextureResolution = EditorGUILayout.IntField("Min Resolution", settings.minTextureResolution);
    260.                 settings.maxTextureResolution = EditorGUILayout.IntField("Max Resolution", settings.maxTextureResolution);
    261.                 settings.minTextureResolution = Mathf.Max(2, settings.minTextureResolution);
    262.                 settings.maxTextureResolution = Mathf.Max(settings.minTextureResolution, settings.maxTextureResolution);
    263.                 EditorGUILayout.BeginHorizontal();
    264.                 if (GUILayout.Button("Bake"))
    265.                 {
    266.                     CaptureMaterial (lastMaterial);
    267.                 }
    268.                 if (GUILayout.Button("Bake Selected"))
    269.                 {
    270.                     scheduleBakeOnNextUpdate = true;
    271.                 }
    272.                 EditorGUILayout.EndHorizontal();
    273.             EditorGUILayout.EndVertical();
    274.             texViewScrollPosition = EditorGUILayout.BeginScrollView (texViewScrollPosition);
    275.                 var r = GUILayoutUtility.GetAspectRect(1.0f);
    276.                 if (previewTexture)
    277.                     EditorGUI.DrawPreviewTexture(r, previewTexture);
    278.             EditorGUILayout.EndScrollView();      
    279.         EditorGUILayout.EndHorizontal();
    280.         if (GUI.changed)
    281.         {
    282.             stateChanged = true;
    283.         }
    284.     }
    285.     @MenuItem("Custom/Bake Material ...", false, 5)
    286.     static function CreateBakeEditor()
    287.     {
    288.         var window = EditorWindow.GetWindow(BakeMaterial);
    289.         window.title = "Bake Material";
    290.         window.minSize = kWindowMinSize;
    291.         window.Show();
    292.     }
    293.     @MenuItem("Custom/Bake Selected Materials", false, 4)
    294.     static function Bake()
    295.     {
    296.         var instanceIDs = Selection.instanceIDs;
    297.         var currentScene = EditorApplication.currentScene;
    298.         var wasAlreadyVisible = BakeMaterial.visible;
    299.         var window = EditorWindow.GetWindow(BakeMaterial);
    300.         if (window.settings.emptyScene)
    301.         {
    302.             if (!EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    303.                 return;
    304.             EditorApplication.NewScene ();
    305.         }
    306.         window.SetupScene ();
    307.         for (var i in instanceIDs)
    308.         {
    309.             var m : Material = EditorUtility.InstanceIDToObject (i) as Material;
    310.             if (m)
    311.                 window.CaptureMaterial (m);
    312.         }
    313.         window.DestroyScene ();
    314.         if (window.settings.emptyScene && currentScene)
    315.         {
    316.             EditorApplication.OpenScene (currentScene);
    317.         }
    318.         if (!wasAlreadyVisible)
    319.             window.Close ();
    320.     }
    321.     static function FindLargestTextureResolution (m : Material, minTexRes : int, maxTexRes : int) : Vector2
    322.     {
    323.         var res = Vector2 (minTexRes, minTexRes);
    324.         for (var n in BakeMaterialSettings.kStandardTexNames)
    325.         {
    326.             if (!m.HasProperty (n))
    327.                 continue;
    328.             var t : Texture = m.GetTexture (n);
    329.             if (!t)
    330.                 continue;
    331.             res.x = Mathf.Max (res.x, t.width);
    332.             res.y = Mathf.Max (res.y, t.height);
    333.         }
    334.         res.x = Mathf.Min (res.x, maxTexRes);
    335.         res.y = Mathf.Min (res.y, maxTexRes);
    336.         return res;
    337.     }
    338.     static function RenderCameraToRenderTexture (cam : Camera, width : int, height : int) : RenderTexture
    339.     {
    340.         var rt = cam.GetComponent.<Camera>().targetTexture;
    341.         if (rt && rt.width != width && rt.height != height)
    342.             DestroyImmediate(rt);
    343.         if (!rt)
    344.             rt = new RenderTexture (width, height, 24);
    345.         cam.GetComponent.<Camera>().targetTexture = rt;
    346.         cam.GetComponent.<Camera>().Render ();
    347.         return rt;
    348.     }
    349.     static function RenderTextureToPNG (rt : RenderTexture, bakeAlpha : boolean, assetPath : String)
    350.     {
    351.         RenderTexture.active = rt;
    352.         var screenShot = new Texture2D (rt.width, rt.height, bakeAlpha? TextureFormat.ARGB32 : TextureFormat.RGB24, false);
    353.         screenShot.ReadPixels (Rect (0, 0, rt.width, rt.height), 0, 0);
    354.         RenderTexture.active = null;
    355.         var bytes = screenShot.EncodeToPNG ();
    356.         System.IO.File.WriteAllBytes (assetPath, bytes);
    357.         AssetDatabase.ImportAsset (assetPath, ImportAssetOptions.ForceUpdate);
    358.     }
    359. }
     

    Attached Files:

    Agent0023 and idurvesh like this.
  18. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    882
    Good Game this give very interessing rendering
    working with matcap
     
  19. pasoca

    pasoca

    Joined:
    Nov 19, 2015
    Posts:
    1
    Hi ,Everyone ,and excuse me for my english.
    I have a little trouble.Can I with this script bake material from selected object ? Because, I need to bake shadows and highlight from object.
     
  20. idurvesh

    idurvesh

    Joined:
    Jun 9, 2014
    Posts:
    493
    Thanks for script though nothing is changing in script....


    **edit**
    Getting this errors
    Code (CSharp):
    1. Releasing render texture that is set as Camera.targetTexture!
    2. UnityEngine.Object:DestroyImmediate(Object)
    3. BakeMaterial:RenderCameraToRenderTexture(Camera, Int32, Int32) (at Assets/Editor/BakeMaterial.js:342)
    4. BakeMaterial:UpdateMaterialPreview(Material) (at Assets/Editor/BakeMaterial.js:151)
    5. BakeMaterial:CaptureMaterial(Material) (at Assets/Editor/BakeMaterial.js:163)
    6. BakeMaterial:BakeMaterial$CaptureMaterial$UnityEngine.Material(Object, Object[])
    7. UnityScript.Lang.UnityRuntimeServices:Invoke(Object, String, Object[], Type)
    8. BakeMaterial:Bake() (at Assets/Editor/BakeMaterial.js:311)
    9. BakeMaterial:Update() (at Assets/Editor/BakeMaterial.js:192)
    10. UnityEditor.EditorApplication:Internal_CallUpdateFunctions()
    11.  
    **edit 2**
    its working,my shaders were unlit..damn
     
  21. xionchannel

    xionchannel

    Joined:
    Mar 30, 2015
    Posts:
    1
    Works with 5.3
    C# version

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections;
    4.  
    5. /*
    6.     Instructions:
    7.     1.Select material to bake
    8.     2.Go Custom/Bake Material...
    9. */
    10. class BakeMaterialSettings
    11. {
    12.     static public string[] kStandardTexNames = { "_MainTex", "_BumpMap", "_Detail", "_ParallaxMap" /*, "_Parallax"*/ };
    13.     static public int kLights = 3;
    14.     static public int kBakingLayerShouldBeUnusedInScene = 30;
    15.  
    16.     public bool bakeAlpha = false;
    17.     public bool bakeMainTexAsWhite = false;
    18.     public int minTextureResolution = 8;
    19.     public int maxTextureResolution = 2048;
    20.     public bool emptyScene = false;
    21.     public bool useCustomLights = false;
    22.     public Color ambient = Color.black;
    23.     public bool[] enableLight = new bool[kLights];
    24.     public Color[] colorLight = new Color[kLights];
    25.     public Vector2[] dirLight = new Vector2[kLights];
    26.  
    27.     private static string kEditorPrefsName = "BakeMaterialSettings";
    28.  
    29.     public BakeMaterialSettings()
    30.     {
    31.         Load();
    32.     }
    33.  
    34.     public void Load ()
    35.     {
    36.         bakeAlpha = EditorPrefs.GetBool(kEditorPrefsName + ".bakeAlpha");
    37.         bakeMainTexAsWhite = EditorPrefs.GetBool(kEditorPrefsName + ".bakeMainTexAsWhite");
    38.         minTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".minTextureResolution", 8);
    39.         maxTextureResolution = EditorPrefs.GetInt(kEditorPrefsName + ".maxTextureResolution", 2048);
    40.         emptyScene = EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene");
    41.         useCustomLights = EditorPrefs.GetBool(kEditorPrefsName + ".useCustomLights");
    42.         ambient.r = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.r");
    43.         ambient.g = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.g");
    44.         ambient.b = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.b");
    45.         ambient.a = EditorPrefs.GetFloat(kEditorPrefsName + ".ambient.a", 1.0f);
    46.         for (var q = 0; q < kLights; ++q)
    47.         {
    48.             enableLight[q] = EditorPrefs.GetBool(kEditorPrefsName + ".enableLight" + q);
    49.             colorLight[q].r = EditorPrefs.GetFloat(kEditorPrefsName + ".color.r" + q, 0.5f);
    50.             colorLight[q].g = EditorPrefs.GetFloat(kEditorPrefsName + ".color.g" + q, 0.5f);
    51.             colorLight[q].b = EditorPrefs.GetFloat(kEditorPrefsName + ".color.b" + q, 0.5f);
    52.             colorLight[q].a = EditorPrefs.GetFloat(kEditorPrefsName + ".color.a" + q, 1.0f);
    53.             dirLight[q].x = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.x" + q);
    54.             dirLight[q].y = EditorPrefs.GetFloat(kEditorPrefsName + ".dir.y" + q);
    55.         }
    56.     }
    57.  
    58.     public void Save ()
    59.     {
    60.         EditorPrefs.SetBool(kEditorPrefsName + ".bakeAlpha", bakeAlpha);
    61.         EditorPrefs.SetBool(kEditorPrefsName + ".bakeMainTexAsWhite", bakeMainTexAsWhite);
    62.         EditorPrefs.SetInt(kEditorPrefsName + ".minTextureResolution", minTextureResolution);
    63.         EditorPrefs.SetInt(kEditorPrefsName + ".maxTextureResolution", maxTextureResolution);
    64.         EditorPrefs.GetBool(kEditorPrefsName + ".emptyScene", emptyScene);
    65.         EditorPrefs.SetBool(kEditorPrefsName + ".useCustomLights", useCustomLights);
    66.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.r", ambient.r);
    67.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.g", ambient.g);
    68.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.b", ambient.b);
    69.         EditorPrefs.SetFloat(kEditorPrefsName + ".ambient.a", ambient.a);
    70.         for (var q = 0; q < kLights; ++q)
    71.         {
    72.             EditorPrefs.SetBool(kEditorPrefsName + ".enableLight" + q, enableLight[q]);
    73.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.r" + q, colorLight[q].r);
    74.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.g" + q, colorLight[q].g);
    75.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.b" + q, colorLight[q].b);
    76.             EditorPrefs.SetFloat(kEditorPrefsName + ".color.a" + q, colorLight[q].a);
    77.             EditorPrefs.SetFloat(kEditorPrefsName + ".dir.x" + q, dirLight[q].x);
    78.             EditorPrefs.SetFloat(kEditorPrefsName + ".dir.y" + q, dirLight[q].y);
    79.         }
    80.     }
    81. }
    82.  
    83. class BakeMaterial : UnityEditor.EditorWindow
    84. {
    85.     private static BakeMaterialSettings settings;
    86.     private static string kMateriBakeNodeName = "__MateriaBakeSetup";
    87.     private static Vector2 kWindowMinSize = new Vector2 (300, 386);
    88.     private static bool visible = false;
    89.     private GameObject camera;
    90.     private GameObject plane;
    91.     private Texture previewTexture;
    92.     private GameObject[] lights = new GameObject[BakeMaterialSettings.kLights];
    93.     private bool stateChanged = false;
    94.     private Vector2 texViewScrollPosition = Vector2.zero;
    95.     private Material lastMaterial;
    96.     private string originalScene = "";
    97.     private bool scheduleBakeOnNextUpdate = false;
    98.  
    99.     private void SetupScene ()
    100.     {
    101.         DestroyScene ();
    102.         var oldGo = GameObject.Find(kMateriBakeNodeName);
    103.         if (oldGo)
    104.             DestroyImmediate (oldGo);
    105.         camera = new GameObject(kMateriBakeNodeName, typeof(Camera));
    106.         plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
    107.         var cam = camera;
    108.         cam.GetComponent<Camera>().backgroundColor = Color.black;
    109.         cam.GetComponent<Camera>().clearFlags = CameraClearFlags.SolidColor;
    110.         cam.GetComponent<Camera>().orthographic = true;
    111.         cam.GetComponent<Camera>().orthographicSize = 5.0f;
    112.         cam.GetComponent<Camera>().cullingMask = 1 << BakeMaterialSettings.kBakingLayerShouldBeUnusedInScene;
    113.         plane.transform.parent = cam.transform;
    114.         plane.transform.position = Vector3.forward * 10.0f;
    115.         plane.transform.rotation = Quaternion.Euler (0f, 0f, 180f) * Quaternion.Euler (-90f, 0f, 0f);
    116.         plane.layer = BakeMaterialSettings.kBakingLayerShouldBeUnusedInScene;
    117.         for (int i=0; i<lights.Length; i++)
    118.         {
    119.             lights[i] = new GameObject("Light", typeof(Light));
    120.             lights[i].GetComponent<Light>().type = LightType.Directional;
    121.             lights[i].GetComponent<Light>().cullingMask = 1 << BakeMaterialSettings.kBakingLayerShouldBeUnusedInScene;
    122.             lights[i].transform.parent = cam.transform;
    123.             lights[i].SetActive(false);
    124.         }
    125.     }
    126.  
    127.     private void UpdateScene (Material m)
    128.     {
    129.         for (int q = 0; q < BakeMaterialSettings.kLights; ++q)
    130.         {
    131.             lights[q].SetActive(settings.useCustomLights && settings.enableLight[q]);
    132.             lights[q].GetComponent<Light>().color = settings.colorLight[q];
    133.             lights[q].transform.rotation =
    134.                 Quaternion.AngleAxis(settings.dirLight[q].x, Vector3.up) *
    135.                 Quaternion.AngleAxis(settings.dirLight[q].y, Vector3.right);
    136.         }
    137.         if (settings.useCustomLights)
    138.             RenderSettings.ambientLight = settings.ambient;
    139.         else if (settings.emptyScene)
    140.             RenderSettings.ambientLight = Color.white;
    141.         plane.GetComponent<Renderer>().material = m;
    142.     }
    143.  
    144.     private void DestroyScene ()
    145.     {
    146.         GameObject.DestroyImmediate (camera);
    147.         GameObject.DestroyImmediate (plane);
    148.         GameObject.DestroyImmediate (previewTexture);
    149.     }
    150.  
    151.     RenderTexture UpdateMaterialPreview (Material m)
    152.     {
    153.         if (!m)
    154.             return null;
    155.         var saveAmbientLight = RenderSettings.ambientLight;
    156.         var saveMainTexture = m.mainTexture;
    157.         if (settings.bakeMainTexAsWhite)
    158.             m.mainTexture = null;
    159.         // setup
    160.         if (!camera)
    161.             SetupScene ();
    162.         camera.SetActive(true);
    163.         UpdateScene (m);
    164.         var res = FindLargestTextureResolution(plane.GetComponent<Renderer>().sharedMaterial, settings.minTextureResolution, settings.maxTextureResolution);
    165.         var rt = RenderCameraToRenderTexture(camera.GetComponent<Camera>(), (int)res.x, (int)res.y);
    166.         // restore
    167.         camera.SetActive(false);
    168.         RenderSettings.ambientLight = saveAmbientLight;
    169.         m.mainTexture = saveMainTexture;
    170.         previewTexture = rt;
    171.         return rt;
    172.     }
    173.  
    174.     void CaptureMaterial(Material m)
    175.     {
    176.         var matAssetPath = AssetDatabase.GetAssetPath (m);
    177.         var assetPath = System.IO.Path.Combine (System.IO.Path.GetDirectoryName (matAssetPath), System.IO.Path.GetFileNameWithoutExtension (matAssetPath));
    178.         var rt = UpdateMaterialPreview (m);
    179.         RenderTextureToPNG (rt, settings.bakeAlpha, assetPath + ".png");
    180.     }
    181.  
    182.     void OnEnable ()
    183.     {
    184.         if (settings == null)
    185.             settings = new BakeMaterialSettings ();
    186.         SetupScene ();
    187.         visible = true;
    188.     }
    189.  
    190.     void OnDisable ()
    191.     {
    192.         DestroyScene ();
    193.         settings.Save ();
    194.         visible = false;
    195.     }
    196.  
    197.     static Material GetTargetMaterial()
    198.     {
    199.         return EditorUtility.InstanceIDToObject (Selection.activeInstanceID) as Material;
    200.     }
    201.  
    202.     void OnSelectionChange ()
    203.     {
    204.         Repaint ();
    205.     }
    206.  
    207.     void Update ()
    208.     {
    209.         var rebuildScene = false;
    210.         if (scheduleBakeOnNextUpdate)
    211.         {
    212.             Bake ();
    213.             scheduleBakeOnNextUpdate = false;
    214.             rebuildScene = true;
    215.         }
    216.         if (originalScene == "" && EditorApplication.currentScene == "")
    217.             settings.emptyScene = true;
    218.         if (settings.emptyScene && originalScene == "" && EditorApplication.currentScene != "")
    219.         {
    220.             DestroyScene ();
    221.             if (EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    222.             {
    223.                 originalScene = EditorApplication.currentScene;
    224.                 EditorApplication.NewScene ();
    225.             }
    226.             else
    227.                 settings.emptyScene = false;
    228.             rebuildScene = true;      
    229.         }
    230.         else if (!settings.emptyScene && originalScene != "")
    231.         {
    232.             EditorApplication.OpenScene (originalScene);
    233.             rebuildScene = true;
    234.             originalScene = "";
    235.         }
    236.         if (rebuildScene)
    237.         {
    238.             SetupScene ();
    239.         }
    240.         if (rebuildScene || stateChanged || !settings.emptyScene)
    241.         {
    242.             UpdateMaterialPreview (lastMaterial);
    243.             Repaint ();
    244.             stateChanged = false;
    245.         }
    246.     }
    247.  
    248.     void OnGUI ()
    249.     {
    250.         var material = GetTargetMaterial ();
    251.         if (lastMaterial != material)
    252.             UpdateMaterialPreview (material);
    253.         if (material)
    254.             lastMaterial = material;
    255.         EditorGUILayout.BeginHorizontal();
    256.             EditorGUILayout.BeginVertical(GUILayout.MaxWidth(200));
    257.                 if (!(originalScene == "" && EditorApplication.currentScene == ""))
    258.                 {
    259.                     settings.emptyScene = !EditorGUILayout.BeginToggleGroup("Scene ligthing", !settings.emptyScene);
    260.                     EditorGUILayout.EndToggleGroup();
    261.                 }
    262.                 settings.useCustomLights = EditorGUILayout.BeginToggleGroup("Custom lighting", settings.useCustomLights);
    263.                 if (settings.useCustomLights)
    264.                 {
    265.                     EditorGUI.indentLevel = 1;
    266.                     settings.ambient = EditorGUILayout.ColorField("Ambient", settings.ambient);
    267.                     for (var q = 0; q < BakeMaterialSettings.kLights; ++q)
    268.                     {
    269.                         settings.enableLight[q] = EditorGUILayout.BeginToggleGroup("Light", settings.enableLight[q]);
    270.                         EditorGUI.indentLevel = 2;
    271.                             settings.colorLight[q] = EditorGUILayout.ColorField("Color", settings.colorLight[q]);
    272.                             settings.dirLight[q] = EditorGUILayout.Vector2Field("Direction", settings.dirLight[q]);
    273.                         EditorGUILayout.EndToggleGroup();
    274.                     }
    275.                 }
    276.                 EditorGUI.indentLevel = 0;
    277.                 EditorGUILayout.EndToggleGroup();
    278.                 settings.bakeAlpha = EditorGUILayout.Toggle("Bake Alpha", settings.bakeAlpha);
    279.                 settings.bakeMainTexAsWhite = !EditorGUILayout.Toggle("MainTex", !settings.bakeMainTexAsWhite);
    280.                 settings.minTextureResolution = EditorGUILayout.IntField("Min Resolution", settings.minTextureResolution);
    281.                 settings.maxTextureResolution = EditorGUILayout.IntField("Max Resolution", settings.maxTextureResolution);
    282.                 settings.minTextureResolution = Mathf.Max(2, settings.minTextureResolution);
    283.                 settings.maxTextureResolution = Mathf.Max(settings.minTextureResolution, settings.maxTextureResolution);
    284.                 EditorGUILayout.BeginHorizontal();
    285.                 if (GUILayout.Button("Bake"))
    286.                 {
    287.                     CaptureMaterial (lastMaterial);
    288.                 }
    289.                 if (GUILayout.Button("Bake Selected"))
    290.                 {
    291.                     scheduleBakeOnNextUpdate = true;
    292.                 }
    293.                 EditorGUILayout.EndHorizontal();
    294.             EditorGUILayout.EndVertical();
    295.             texViewScrollPosition = EditorGUILayout.BeginScrollView (texViewScrollPosition);
    296.                 var r = GUILayoutUtility.GetAspectRect(1.0f);
    297.                 if (previewTexture)
    298.                     EditorGUI.DrawPreviewTexture(r, previewTexture);
    299.             EditorGUILayout.EndScrollView();  
    300.         EditorGUILayout.EndHorizontal();
    301.         if (GUI.changed)
    302.         {
    303.             stateChanged = true;
    304.         }
    305.     }
    306.  
    307.     [MenuItem("Custom/Bake Material", false, 5)]
    308.     static void CreateBakeEditor()
    309.     {
    310.         var window = UnityEditor.EditorWindow.GetWindow<BakeMaterial>("Bake Material");
    311.         window.minSize = kWindowMinSize;
    312.         window.Show();
    313.     }
    314.  
    315.     [MenuItem("Custom/Bake Selected Materials", false, 4)]
    316.     static void Bake()
    317.     {
    318.         var instanceIDs = Selection.instanceIDs;
    319.         var currentScene = EditorApplication.currentScene;
    320.         var wasAlreadyVisible = BakeMaterial.visible;
    321.         var window = UnityEditor.EditorWindow.GetWindow<BakeMaterial>("Bake Selected Material");
    322.         if (BakeMaterial.settings.emptyScene)
    323.         {
    324.             if (!UnityEditor.EditorApplication.SaveCurrentSceneIfUserWantsTo ())
    325.                 return;
    326.             UnityEditor.EditorApplication.NewScene ();
    327.         }
    328.         window.SetupScene ();
    329.         foreach (var i in instanceIDs)
    330.         {
    331.             Material m = UnityEditor.EditorUtility.InstanceIDToObject(i) as Material;
    332.             if (m)
    333.                 window.CaptureMaterial (m);
    334.         }
    335.         window.DestroyScene ();
    336.         if (BakeMaterial.settings.emptyScene && currentScene != "")
    337.         {
    338.             UnityEditor.EditorApplication.OpenScene(currentScene);
    339.         }
    340.         if (!wasAlreadyVisible)
    341.             window.Close ();
    342.     }
    343.  
    344.     static Vector2 FindLargestTextureResolution (Material m, int minTexRes, int maxTexRes)
    345.     {
    346.         Vector2 res = new Vector2 (minTexRes, minTexRes);
    347.         foreach (var n in BakeMaterialSettings.kStandardTexNames)
    348.         {
    349.             if (!m.HasProperty(n))
    350.                 continue;
    351.             Texture t = m.GetTexture(n);
    352.             if (!t)
    353.                 continue;
    354.             res.x = Mathf.Max(res.x, t.width);
    355.             res.y = Mathf.Max(res.y, t.height);
    356.         }
    357.         res.x = Mathf.Min (res.x, maxTexRes);
    358.         res.y = Mathf.Min (res.y, maxTexRes);
    359.         return res;
    360.     }
    361.  
    362.     static RenderTexture RenderCameraToRenderTexture (Camera cam, int width, int height)
    363.     {
    364.         var rt = cam.GetComponent<Camera>().targetTexture;
    365.         if (rt && rt.width != width && rt.height != height)
    366.             DestroyImmediate(rt);
    367.         if (!rt)
    368.             rt = new RenderTexture (width, height, 24);
    369.         cam.GetComponent<Camera>().targetTexture = rt;
    370.         cam.GetComponent<Camera>().Render ();
    371.         return rt;
    372.     }
    373.  
    374.     static void RenderTextureToPNG (RenderTexture rt, bool bakeAlpha, string assetPath)
    375.     {
    376.         RenderTexture.active = rt;
    377.         var screenShot = new Texture2D (rt.width, rt.height, bakeAlpha? TextureFormat.ARGB32 : TextureFormat.RGB24, false);
    378.         screenShot.ReadPixels (new Rect(0, 0, rt.width, rt.height), 0, 0);
    379.         RenderTexture.active = null;
    380.         var bytes = screenShot.EncodeToPNG ();
    381.         System.IO.File.WriteAllBytes (assetPath, bytes);
    382.         AssetDatabase.ImportAsset (assetPath, ImportAssetOptions.ForceUpdate);
    383.     }
    384. }