Search Unity

Problems with instantiating baked prefabs

Discussion in 'Global Illumination' started by GSdev, May 8, 2015.

Thread Status:
Not open for further replies.
  1. Hunduan2015

    Hunduan2015

    Joined:
    Jan 13, 2017
    Posts:
    2
    Terrain renderer component is null? How is terrain supported, i can't understand the details? can you tell me, thanks very mach!
     
  2. TheShock

    TheShock

    Joined:
    Aug 5, 2014
    Posts:
    35
    Hi guys. Those scripts are awesome, but what about Lightprobes? Prefab lightmaps are shown correctly, but lightprobes in prefab dont work. Are there way to make lightprobes work in prefabs?
     
  3. geroppo

    geroppo

    Joined:
    Dec 24, 2012
    Posts:
    140
    I'm also having problems with lightprobes...I'm using realtime GI, is it even possible at all to make them work?
     
  4. jmgantz

    jmgantz

    Joined:
    Nov 7, 2012
    Posts:
    4
    static void ApplyRendererInfo(RendererInfo[] infos, int[] arrayOffsetIndex)
    {
    for (int i = 0; i < infos.Length; i++)
    {
    var info = infos;
    if(info.renderer == null)
    {
    Debug.Log("<color=red> ===ERROR NO RENDER</color>");
    continue;
    }
    info.renderer.lightmapIndex = arrayOffsetIndex[info.lightmapIndex];
    info.renderer.lightmapScaleOffset = info.lightmapOffsetScale;

    // You have to release shaders.
    Material[] mat = info.renderer.sharedMaterials;
    for (int j = 0; j < mat.Length; j++)
    {
    if(mat[j] != null)
    mat[j].shader = Shader.Find(mat[j].shader.name);
    }
    }
    }


    If you can't see fog on the assetbundle version. You can use this code. I think we have to reset shaders.
     
  5. migiesmith

    migiesmith

    Joined:
    Mar 1, 2017
    Posts:
    1
    I found that when using this script, the lightmap would use a lot of memory. In my case there would be 104 lightmaps, resulting in 460MBs for lightmaps dropping the fps significantly. With my changes, the prefabs check the lightmap for matching hashcodes to determine if the lightmap already exists and can be shared with another prefab. Doing so means that I can have the same number of prefabs for a fraction of the memory. Only 2 lightmaps from 104.

    Edit: probably needs updated to get the correct index of any lightmaps that were not found but I don't currently have any that do that so I wouldn't really be able to test it of I made the changes.
     

    Attached Files:

    Last edited: Mar 2, 2017
  6. racsoh

    racsoh

    Joined:
    Aug 6, 2016
    Posts:
    9
    Hi,
    Did anyone ever found a proper solution to the problem?
    I'm using Unity 5.5.2f1 and still no built-in solution.
    I'm using the original script provided @idurvesh with the Editor Extension and the PrefabLightmapData.cs.
    This solution only works with 1 Prefab, but it doesn't work when you work with multiple prefabs. I've tried everything, all the settings suggested here, baked all prefabs on the scene,the lightmaps are always broken when the prefabs are instantiated.

    After I baked my prefabs on the scene they look fine but once they are instantiated the Lightmaps are incorrect.

    Does anyone have an updated version of these scripts that actually work. I've spend countless hours on this already and it's really frustrating. I don't understand how Unity Team, knowing that this is essential for mobile(btw my game is for Android) have not come up with a proper solution for this. I understand it was removed on Unity 5 for xyz reasons, but they should provide a working example.

    Note to Unity Team: Please noticed that assigning lightmaps manually is not a doable solution when the Prefabs are to complex or multiple prefabs are used.

    Any help, guide or direction is greatly appreciated. Thanks in advance.
     
    Ruslank100 likes this.
  7. Astiolo

    Astiolo

    Joined:
    Dec 18, 2014
    Posts:
    27
    I tried that one without success. There are many in this long forum with slight changes. What's currently working for me is the one I posted in post number 300. If that doesn't work for you then just have a read through and give some other ones a go.

    I really wish Unity would implement this functionality properly, but for now the scripts in this forum seem to be the best option(s).
     
    Ruslank100 likes this.
  8. racsoh

    racsoh

    Joined:
    Aug 6, 2016
    Posts:
    9
    Thanks @Astiolo. I'll give it a try today afternoon and I'll report back. Do you have any specific settings on your Light baking settings that you suggest implementing with this script.
     
  9. racsoh

    racsoh

    Joined:
    Aug 6, 2016
    Posts:
    9
    Hey @Astiolo. Anything special I need to do with script on post #300. It didn't work for me. After I created my list of pool objects my prefabs had no Lightmaps at all.
     
  10. idurvesh

    idurvesh

    Joined:
    Jun 9, 2014
    Posts:
    495
  11. racsoh

    racsoh

    Joined:
    Aug 6, 2016
    Posts:
    9
    First of all - BIG THANKS to all of you.

    Finally o_O after a lot of trial and error I was able to use one of the scripts that worked, at least for me.

    I've used the original PrefabLightmapData.cs from the project posted by the Unity Team in the post #6.

    I've put together a little guide bellow for who may need help with this issue.
    I've also attached all the details like the Lighting Settings, the screenshots of the Prefabs after the Lightmap was baked, etc.

    Steps followed:
    1 - Build your Prefabs with your lights on it (Tip: Used and empty GameObject to group all the lights under that Prefab - will turn the lights off later, but will keep them in case we want to change it later on)
    2 - Set your Prefab as Static (apply to all children).
    3 - Under Static drop down menu, be sure Batching Static is checked OFF, for all the children under the parent GameObject and the parent itself.
    4 - Place the script PrefabLightmapData.cs on the parent GameObject of the Prefab.
    5 - On the Main Menu click on Assets > Bake Prefabs Lightmap.
    6 - When the Baking is completed, disable the GameObject with all the lights on the Prefab(s)
    7 - Click Apply button on the Inspector to apply all the changes to you Prefab.

    I'm using this script on my Prebafs that are part of random generated paths using pooling. I also tested this on Android 7.0 successfully, and Unity 5.5.2f1. Lightmaps are working as excepted.

    What I did not tried was to use Light Probes.

    Important note: If you try to use any of these scripts to generate Lightmaps for objects created with ProBuilder don't waste your time, it doesn't work. After baking, the Lightmaps looks fine on the scene, but when they are instantiated it doesn't display correctly.
     

    Attached Files:

    Last edited: Mar 5, 2017
  12. Shtrude1

    Shtrude1

    Joined:
    Nov 5, 2016
    Posts:
    15
    I have a question regarding the prefab.
    I've done everything its said in the steps and yet when i instantiate the prefab it loses its look.(I am not using ProBuilder)
    Also for some reason when the baking is done the script is doubled.
    Here is the example of the issue:
     

    Attached Files:

  13. racsoh

    racsoh

    Joined:
    Aug 6, 2016
    Posts:
    9
    Use the script attached below (it should be the same, but just in case). I think initially it duplicates, but I can really recall now. If that happens just remove the duplicate. Can you upload a small video to see the steps you followed. Also can you please provide the Unity version you are working with.
     

    Attached Files:

  14. Shtrude1

    Shtrude1

    Joined:
    Nov 5, 2016
    Posts:
    15
    I am using Unity 5.5.2f1
     
  15. UnityLighting

    UnityLighting

    Joined:
    Mar 31, 2015
    Posts:
    3,874
    5.5.2f1 is completely broken. It's has a lot of issues. I recommend you to use 5.2.1 instead. It'a more stable.
     
  16. racsoh

    racsoh

    Joined:
    Aug 6, 2016
    Posts:
    9
    Hi @Shtrude1, I just watched you video. I must say, I'm doing my baking with actual lights, I have not tried using Emission Materials. Here's a small video demonstrating what I described above. Take a look:

     
    Last edited: Mar 7, 2017
  17. racsoh

    racsoh

    Joined:
    Aug 6, 2016
    Posts:
    9
    I ran a test using Emission Materials and everything is working fine as well. Take a look:



    I found that I get betters result when using textures instead of the plain color.

    To bake multiple prefabs, just dump all your prefabs on your scene and separate them so the light don't bounce between prefabs, then apply the changes to the prefabs after the baking is completed.
     
    Last edited: Mar 7, 2017
  18. Shtrude1

    Shtrude1

    Joined:
    Nov 5, 2016
    Posts:
    15
    Huh, well it works fine now , thx for the help tho.
     
  19. UnityLighting

    UnityLighting

    Joined:
    Mar 31, 2015
    Posts:
    3,874
    I wrote a new simple script for my game :
    * This needs baked prefab to be on the scene , you can not delete(you can disable mesh renderers)
    * Tested in android build (i don't know anything about performance for now)

     

    Attached Files:

    Last edited: Mar 7, 2017
  20. UnityLighting

    UnityLighting

    Joined:
    Mar 31, 2015
    Posts:
    3,874
    I have updated LightmapBase script to disable mesh renderers automatically in base baked prefab (In my case needs to be disabled for performance reasons , i just used instantiated prefabs)


    How to disable mesh renderer on start :


    Code (CSharp):
    1.     void Start () {
    2.  
    3.         Renderer[] r = GetComponentsInChildren<Renderer>();
    4.  
    5.  
    6.         foreach(Renderer rr in r)
    7.             rr.enabled = false;
    8.     }
     
  21. zorgonski

    zorgonski

    Joined:
    Feb 14, 2013
    Posts:
    4
    Hey guys, getting stuck here...

    So, I'm succesfully baking the lightmaps, adding the renderinfo to prefab and applying it to the prefab, making an asset bundle of it then loading it at runtime and applying the map..., BUT only when I do this in the scene in which I made prefab. If I choose to load prefab with lightmap data into a different scene (even without asset-bundling it), i lose everything...is there a way to use the prefab with ligthmap data attached in the scenes that it wasn't baked in? I saw a hint where you can "loading additive" the "level" with the prefab in it...seems messy.

    Not sure why I can't use prefab with other scenes, it doesn't rely on location of the lightmaps, and it contains data about them...

    Puzzling....
     
  22. Haru_Happy

    Haru_Happy

    Joined:
    Sep 4, 2015
    Posts:
    11
    hey guys,new problem
    sorry my english...

    i bake succ and made it to prefab, and if drag prefab to scene and click play button(make it run-time) looks good ,but when i build to assetbundle and loaded it ,it was terrify,

    load prefab :
    1.jpg

    load assetbundle:
    2.jpg

    dose anyone can solve it?
     
  23. Haru_Happy

    Haru_Happy

    Joined:
    Sep 4, 2015
    Posts:
    11
    ok it was sovled... run on mobile is good , just pc is wrong.....
     
  24. nindim

    nindim

    Joined:
    Jan 22, 2013
    Posts:
    130
    @idurvesh

    Hi,

    I have done some initial tests and things looks promising!

    I re-created your script to set the Light.BakedIndex, but this has been made obsolete in Unity 5.6 (I'm using 5.6.0f2). It tells us to use Light.IsBaked instead, but this is read-only. Any ideas what we should be doing instead?

    Cheers,

    Niall

     
  25. TJShae

    TJShae

    Joined:
    Dec 20, 2016
    Posts:
    1
    @racsoh

    Hey there

    Your instructions above, and accompanying youtube vids are much appreciated. However, I have been through the steps many times now with my prefabs and I'm still seeing the same issue every time. When the light maps have been built, the prefab immediately becomes very dark. I am using one directional light (for the shadows from the sun) and one point light around the blacksmith's furnace.

    Here is the prefab whilst the script is running:

    Screen1.png

    And here it is immediately after the script has run (even before I turn the lights off):

    Screen2.png

    I can't help but think that this is something to do with my ambient lighting. I need some ambient light in the scene, otherwise it is all in shadow. When baking the light maps, should this ambient lighting be removed?

    When this prefab is used in the scene with others that I have not yet baked the light maps into, you can see the difference in the lighting:

    Screen4.png

    Here are my scene lighting settings:

    Screen3.png

    Any advice would be much appreciated!

    Thanks
    --TJ
     
    Last edited: Apr 7, 2017
  26. racsoh

    racsoh

    Joined:
    Aug 6, 2016
    Posts:
    9
    Hi @TJShae,

    Sorry it took me so long to reply, I've been really disconnected due to a few projects.
    Please be sure that you have Generate Lightmap UVs checkbox Checked ON for every model you imported (that's what seems to be causing that issue), and then re-bake using the script I uploaded:
     

    Attached Files:

  27. Johnny-Ge

    Johnny-Ge

    Joined:
    Apr 26, 2014
    Posts:
    11
    Hiiii guys, for this topic We have an issue when we use one level to load different baked Prefab.

    https://forum.unity3d.com/threads/problems-with-instantiating-baked-prefabs.324514/#post-2177524
    this script is what we use in project.

    The baked level looks like
    Screen Shot 2017-04-17 at 2.30.07 AM.png
    Everything looks good.

    Load baked prefab looks like Screen Shot 2017-04-17 at 2.31.55 AM.png
    The lightmap is loaded correctly, but the prefab looks not good LOL....

    And we use Unity 5.5.1f1 Pro.
    We are confused by this issue, plz help us , thankssssssss

    @Joachim_Ante
    Would u plz give me some tips, I tried your sample project in 5.3.1 successed, but not good in 5.5.1 or 5.5.2. Thanks!
     
    Last edited: Apr 18, 2017
  28. Prashant_206

    Prashant_206

    Joined:
    Feb 26, 2014
    Posts:
    11
  29. pysnoonh

    pysnoonh

    Joined:
    Dec 15, 2016
    Posts:
    2
    Hello, thank you for the script. I succeed to apply lightmaps in another scene.

    But I have a problem with lightprobes. If position of prefab is different than the scene where you baked, it is impossible to have lightprobes correctly set. Informations of lightprobes (coefficients, number, positions, ...) are stored in LightingData and these information except for coefficients are read only.

    Did anybody find a way to solve this ?
     
  30. Prashant_206

    Prashant_206

    Joined:
    Feb 26, 2014
    Posts:
    11
    Hi Pysnoonh,

    I don't even have light probes in my project. Just directional light and a point light. Also the example given by @Joachim_Ante has lightmaps in the form of 2d texture. This is not generated anymore in new versions 5.5/5.6 when we bake scene. Also I'm changing the transparency/alpha of some materials in runtime through scripts, even they are not working when instantiated through asset bundle. I would really appreciate some help in this. Thanks
     
  31. TheShock

    TheShock

    Joined:
    Aug 5, 2014
    Posts:
    35
    What about 5.6? Looks like prefabs now stores their link to lightmap and you can create lightmapped objects inside one scene, but it still does not load lightmap asset to another scene.
     
  32. pysnoonh

    pysnoonh

    Joined:
    Dec 15, 2016
    Posts:
    2
    I'm using 5.6 and it's not working
     
  33. StaggartCreations

    StaggartCreations

    Joined:
    Feb 18, 2015
    Posts:
    2,263
    Has anyone found the alternative to using Light.bakedIndex? https://docs.unity3d.com/540/Documentation/ScriptReference/Light-bakedIndex.html

    When using prefabs with Mixed lighting this was required to make sure a light does not light objects that already use a baked lightmaps. Otherwise static objects look overexposed.

    In 5.6, it is made obsolete. Bringing forth the problem of "overexposure".

    Video illustrates how static/baked objects are still being lit by the Directional Light, because it cannot be flagged using bakedIndex.


    EDIT: Fixed this by adding a static object to our main scene (which handles all the loading and game states) and baking static lighting. This seemed to have flagged the directional light as baked. We only use that one directional light and change it's rotation according to the level loaded. So this works fine.
     
    Last edited: May 2, 2017
    KRGraphics likes this.
  34. pravusjif

    pravusjif

    Joined:
    Jul 24, 2012
    Posts:
    18
    Hi there, me and my team could get the lightmap baking to work on prefabs using the package posted here.

    Although we found out that if the scene where we instantiate the prefab along with its lightmaps doesn't have a lightmap on its own, the lightmap of the prefab rendered wrong.

    So if anyone has the same problem in which the lightmap renders wrong (as in horribly black & white - only rendering), try baking a lightmap, even a simple one, on that scene first.
     
  35. LunaTrap

    LunaTrap

    Joined:
    Apr 10, 2015
    Posts:
    120
    Hello, I hope I will be able to get an answer, I have used the script that has the editor made by @idurvesh

    It works great, but I would like to be able to bake the lightmapping shadow mask, tried editing the script. but I really don't get it. I'm a bit of a noob :p any help please?

    here is my try at chaging the script

    Code (CSharp):
    1. #if UNITY_EDITOR
    2. using UnityEditor;
    3. #endif
    4. using UnityEngine;
    5. using System.Collections.Generic;
    6. using System.Linq;
    7. public class PrefabLightmapData : MonoBehaviour
    8. {
    9.     [System.Serializable]
    10.     struct RendererInfo
    11.     {
    12.         public List<Renderer> renderer;
    13.         public int lightmapIndex;
    14.         public Vector4 lightmapOffsetScale;
    15.     }
    16.     [SerializeField]
    17.     List<RendererInfo> m_RendererInfo;
    18.     [SerializeField]
    19.     Texture2D[] m_Lightmaps;
    20.     [SerializeField]
    21.     Texture2D[] m_Lightmaps2;
    22.     [SerializeField]
    23.   public  static string LIGHTMAP_RESOURCE_PATH = "Assets/Resources/Lightmaps/";
    24.     [System.Serializable]
    25.     struct Texture2D_Remap
    26.     {
    27.         public int originalLightmapIndex;
    28.         public Texture2D originalLightmap;
    29.         public Texture2D lightmap;
    30.         public Texture2D lightmap2;
    31.     }
    32.     static List<Texture2D_Remap> sceneLightmaps = new List<Texture2D_Remap>();
    33.     void Awake()
    34.     {
    35.  
    36.     }
    37.     // Use this for initialization
    38.     void Start()
    39.     {
    40.         ApplyLightmaps(m_RendererInfo, m_Lightmaps, m_Lightmaps2);
    41.         //StaticBatchingUtility.Combine(this.gameObject);
    42.     }
    43.  
    44.     static void ApplyLightmaps(List<RendererInfo> rendererInfo, Texture2D[] lightmaps, Texture2D[] lightmaps2)
    45.     {
    46.         bool existsAlready = false;
    47.         int counter = 0;
    48.         int[] lightmapArrayOffsetIndex;
    49.         if (rendererInfo == null || rendererInfo.Count == 0)
    50.             return;
    51.         var settingslightmaps = LightmapSettings.lightmaps;
    52.         var combinedLightmaps = new List<LightmapData>();
    53.         lightmapArrayOffsetIndex = new int[lightmaps.Length];
    54.         for (int i = 0; i < lightmaps.Length; i++)
    55.         {
    56.             existsAlready = false;
    57.             for (int j = 0; j < settingslightmaps.Length; j++)
    58.             {
    59.                 if (lightmaps[i] == settingslightmaps[j].lightmapColor)
    60.                 {
    61.                     lightmapArrayOffsetIndex[i] = j;
    62.                     existsAlready = true;
    63.                 }
    64.             }
    65.             if (!existsAlready)
    66.             {
    67.                 lightmapArrayOffsetIndex[i] = counter + settingslightmaps.Length;
    68.                 var newLightmapData = new LightmapData();
    69.                 newLightmapData.lightmapColor = lightmaps[i];
    70.                 newLightmapData.shadowMask = lightmaps2[i];
    71.                 combinedLightmaps.Add(newLightmapData);
    72.                 ++counter;
    73.             }
    74.         }
    75.         var combinedLightmaps2 = new LightmapData[settingslightmaps.Length + combinedLightmaps.Count];
    76.         settingslightmaps.CopyTo(combinedLightmaps2, 0);
    77.         if (counter > 0)
    78.         {
    79.             for (int i = 0; i < combinedLightmaps.Count; i++)
    80.             {
    81.                 combinedLightmaps2[i + settingslightmaps.Length] = new LightmapData();
    82.                 combinedLightmaps2[i + settingslightmaps.Length].lightmapColor = combinedLightmaps[i].lightmapColor;
    83.                 combinedLightmaps2[i + settingslightmaps.Length].shadowMask = combinedLightmaps[i].shadowMask;
    84.             }
    85.         }
    86.         ApplyRendererInfo(rendererInfo, lightmapArrayOffsetIndex);
    87.         LightmapSettings.lightmaps = combinedLightmaps2;
    88.     }
    89.     static void ApplyRendererInfo(List<RendererInfo> infos, int[] arrayOffsetIndex)
    90.     {
    91.         for (int i = 0; i < infos.Count; i++)
    92.         {
    93.             var info = infos[i];
    94.             foreach (Renderer rer in info.renderer)
    95.             {
    96.                 rer.lightmapIndex = arrayOffsetIndex[info.lightmapIndex];
    97.                 rer.lightmapScaleOffset = info.lightmapOffsetScale;
    98.             }
    99.         }
    100.     }
    101. #if UNITY_EDITOR
    102.    // [MenuItem("Assets/Assign lightmaps to LOD")]
    103.    public static void UseMeBeforeUpdatint(string lightMapFix = "LOD")
    104.     {
    105.         PrefabLightmapData[] prefabs = FindObjectsOfType<PrefabLightmapData>();
    106.         foreach (var instance in prefabs)
    107.         {
    108.             List<RendererInfo> tempListOfRender = instance.m_RendererInfo;
    109.             foreach (RendererInfo ren in tempListOfRender)
    110.             {
    111.                 foreach (Renderer re in ren.renderer.ToList())
    112.                 {
    113.                     Transform myParentForSib = re.transform.parent;
    114.                     foreach (var chil in myParentForSib.GetComponentsInChildren<Transform>())
    115.                     {
    116.                         if (chil != ren.renderer[0].transform)
    117.                         {
    118.                             if (chil.gameObject.name.Contains(lightMapFix))
    119.                             {
    120.                                 ren.renderer.Add(chil.GetComponent<MeshRenderer>());
    121.                             }
    122.                         }
    123.                     }
    124.                 }
    125.             }
    126.         }
    127.     }
    128.   //  [MenuItem("Assets/Update Scene with Prefab Lightmaps")]
    129.   public  static void UpdateLightmaps()
    130.     {
    131.         PrefabLightmapData[] prefabs = FindObjectsOfType<PrefabLightmapData>();
    132.         foreach (var instance in prefabs)
    133.         {
    134.             ApplyLightmaps(instance.m_RendererInfo, instance.m_Lightmaps, instance.m_Lightmaps2);
    135.         }
    136.         Debug.Log("Prefab lightmaps updated");
    137.     }
    138. //   [MenuItem("Assets/Bake Prefab Lightmaps")]
    139.   public  static void GenerateLightmapInfo(string folderPath,TextureImporterFormat textureFormat,int textureMaxSize)
    140.     {
    141.         LIGHTMAP_RESOURCE_PATH = folderPath;
    142.         tf = textureFormat;
    143.         sizeOfTexture = textureMaxSize;
    144.  
    145.         Debug.ClearDeveloperConsole();
    146.         if (Lightmapping.giWorkflowMode != Lightmapping.GIWorkflowMode.OnDemand)
    147.         {
    148.             Debug.LogError("ExtractLightmapData requires that you have baked you lightmaps and Auto mode is disabled.");
    149.             return;
    150.         }
    151.         Lightmapping.Bake();
    152.         sceneLightmaps = new List<Texture2D_Remap>();
    153.         var scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
    154.        
    155.  
    156.         var resourcePath = LIGHTMAP_RESOURCE_PATH + scene.name;
    157.         var scenePath = System.IO.Path.GetDirectoryName(scene.path) + "/" + scene.name + "/";
    158.         PrefabLightmapData[] prefabs = FindObjectsOfType<PrefabLightmapData>();
    159.         foreach (var instance in prefabs)
    160.         {
    161.             var gameObject = instance.gameObject;
    162.             var rendererInfos = new List<RendererInfo>();
    163.             var lightmaps = new List<Texture2D>();
    164.             var lightmaps2 = new List<Texture2D>();
    165.             GenerateLightmapInfo(scenePath, resourcePath, gameObject, rendererInfos, lightmaps, lightmaps2);
    166.             instance.m_RendererInfo = rendererInfos;
    167.             instance.m_Lightmaps = lightmaps.ToArray();
    168.             instance.m_Lightmaps2 = lightmaps2.ToArray();
    169.             var targetPrefab = PrefabUtility.GetPrefabParent(gameObject) as GameObject;
    170.             if (targetPrefab != null)
    171.             {
    172.                 //Prefab
    173.                 PrefabUtility.ReplacePrefab(gameObject, targetPrefab);
    174.             }
    175.             ApplyLightmaps(instance.m_RendererInfo, instance.m_Lightmaps, instance.m_Lightmaps2);
    176.         }
    177.         Debug.Log("Update to prefab lightmaps finished");
    178.     }
    179.     static void GenerateLightmapInfo(string scenePath, string resourcePath, GameObject root, List<RendererInfo> rendererInfos, List<Texture2D> lightmaps, List<Texture2D> lightmaps2)
    180.     {
    181.         var renderers = root.GetComponentsInChildren<MeshRenderer>();
    182.         foreach (MeshRenderer renderer in renderers)
    183.         {
    184.             if (renderer.lightmapIndex != -1 && renderer.enabled)
    185.             {
    186.                 RendererInfo info = new RendererInfo();
    187.                 info.renderer = new List<Renderer>();
    188.                 info.renderer.Add(renderer);
    189.                 info.lightmapOffsetScale = renderer.lightmapScaleOffset;
    190.                 Texture2D lightmap = LightmapSettings.lightmaps[renderer.lightmapIndex].lightmapColor;
    191.                 Texture2D lightmap2 = LightmapSettings.lightmaps[renderer.lightmapIndex].shadowMask;
    192.                 int sceneLightmapIndex = AddLightmap(scenePath, resourcePath, renderer.lightmapIndex, lightmap, lightmap2);
    193.                 info.lightmapIndex = lightmaps.IndexOf(sceneLightmaps[sceneLightmapIndex].lightmap);
    194.                 if (info.lightmapIndex == -1)
    195.                 {
    196.                     info.lightmapIndex = lightmaps.Count;
    197.                     lightmaps.Add(sceneLightmaps[sceneLightmapIndex].lightmap);
    198.                     lightmaps2.Add(sceneLightmaps[sceneLightmapIndex].lightmap2);
    199.                 }
    200.                 rendererInfos.Add(info);
    201.             }
    202.         }
    203.     }
    204.     static int AddLightmap(string scenePath, string resourcePath, int originalLightmapIndex, Texture2D lightmap, Texture2D lightmap2)
    205.     {
    206.         int newIndex = -1;
    207.         for (int i = 0; i < sceneLightmaps.Count; i++)
    208.         {
    209.             if (sceneLightmaps[i].originalLightmapIndex == originalLightmapIndex)
    210.             {
    211.                 return i;
    212.             }
    213.         }
    214.         if (newIndex == -1)
    215.         {
    216.             var lightmap_Remap = new Texture2D_Remap();
    217.             lightmap_Remap.originalLightmapIndex = originalLightmapIndex;
    218.             lightmap_Remap.originalLightmap = lightmap;
    219.             var filename = scenePath + "Lightmap-" + originalLightmapIndex;
    220.             lightmap_Remap.lightmap = GetLightmapAsset(filename + "_comp_light.exr", resourcePath + "_light", originalLightmapIndex, lightmap);
    221.             if (lightmap2 != null)
    222.             {
    223.                 lightmap_Remap.lightmap2 = GetLightmapAsset(filename + "_comp_shadowmask.png", resourcePath + "_shadowmask", originalLightmapIndex, lightmap2);
    224.             }
    225.             sceneLightmaps.Add(lightmap_Remap);
    226.             newIndex = sceneLightmaps.Count - 1;
    227.         }
    228.         return newIndex;
    229.     }
    230.  
    231.     public static int sizeOfTexture;
    232.     public static TextureImporterFormat tf;
    233.  
    234.     static Texture2D GetLightmapAsset(string filename, string resourcePath, int originalLightmapIndex, Texture2D lightmap)
    235.     {
    236.         Debug.Log(filename);
    237.         AssetDatabase.ImportAsset(filename, ImportAssetOptions.ForceUpdate);
    238.         var importer = AssetImporter.GetAtPath(filename) as TextureImporter;
    239.         importer.isReadable = true;
    240.         importer.textureFormat = tf;
    241.         importer.maxTextureSize = sizeOfTexture;
    242.  
    243.  
    244.  
    245.         AssetDatabase.ImportAsset(filename, ImportAssetOptions.ForceUpdate);
    246.         var assetLightmap = AssetDatabase.LoadAssetAtPath<Texture2D>(filename);
    247.         var assetPath = resourcePath + "-" + originalLightmapIndex + ".asset";
    248.         var newLightmap = Instantiate<Texture2D>(assetLightmap);
    249.         AssetDatabase.CreateAsset(newLightmap, assetPath);
    250.         newLightmap = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
    251.         importer.isReadable = false;
    252.         AssetDatabase.ImportAsset(filename, ImportAssetOptions.ForceUpdate);
    253.         return newLightmap;
    254.     }
    255. #endif
    256. }
     
  36. StephenHodgson-Valorem

    StephenHodgson-Valorem

    Joined:
    Mar 8, 2017
    Posts:
    148
    MadeFromPolygons likes this.
  37. LunaTrap

    LunaTrap

    Joined:
    Apr 10, 2015
    Posts:
    120
    Can someone please give me an answer :(

    1- Is there a way to use this script to also apply shadow mask to prefabs?

    2-Is there a way to use this script with light probes for procedural content?
     
  38. thefranke

    thefranke

    Unity Technologies

    Joined:
    Jun 20, 2015
    Posts:
    153
    Hey Johnny-Ge,

    I've looked into your issue. The reason this happens is this: Each baked scene has a LightingData asset. Among other things, it sets up how to interpret the lightmaps associated with a scene (for instance whether they are directional or non-directional). But since your main scene, which uses the prefabs, has no LightingData asset, this value is left in an invalid state, so the lightmaps from your script are reproduced like this (something random basically).

    The solution is simple though. Simply press Build in the LightmapInstances scene (make sure it has the same settings as the scene you bake the prefabs in!). It will generate a LightingData asset, set up how to read lightmaps correctly when running and then display the lightmaps correctly.

    Cheers
     
  39. ArtSasil

    ArtSasil

    Joined:
    May 11, 2017
    Posts:
    1
    Could you please upload a video showing how to do this? I can't manage to do exactly what you said. I might be missing something. Thank you very much.
     
  40. KevinGelking

    KevinGelking

    Joined:
    Jul 17, 2014
    Posts:
    15
    Hey folks; we also have issues with lightmaps after upgrading from unity 5.5 to 5.6(.1.p2).
    Due to the upgrade we had to replace the deprecated "bakedIndex". With no replacement, everything (both static baked and dynamic non-baked) objects are lit, causing the baked objects to be overexposed.
    If we tell the lightsource "alreadyLightmapped = true", the baked objects look fine - but all dynamic, non-baked objects are dark, as if the light source were disabled.

    In the editor (not in playmode), all objects look fine, but once the playmode starts the above scenarios come into play.

    As an additional layer of information, which does not apply to the example below, we usually have one scene in which we load a prefab via assetbundle which also contains lighting information that we previously baked and ripped and is used to overwrite the current scene lighting settings. This may or may not be relevant.

    Below you can see a few screenshots demonstrating this issue (with 'alreadyLightmapped = true')

    ^ this is the non-playmode editor view of a non-lightmapped object on static, baked background. The object appears just fine in the baked environment


    ^ the 'baked lightmap' view verifies that the object has no lightmap and should be lit by a "mixed" lightsource


    ^ this is the setup of our lightsource and lighting. In a nutshell we have a single directional lightsource set to mixed and use only mixed lighting baked GI using the enlighten system


    ^ once in playmode, this is how the object appears, despite not having a lightmap



    Am I right to assume that a "mixed lightsource" does NOT illuminate non-baked objects when it is told that things are already lightmapped?
    How could we work around this? Suggestions are welcome :)
     
    Last edited: Jun 20, 2017
    KRGraphics likes this.
  41. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    4,467
    This is exact issue I'm having. I'm gonna have to do a new project and send it to Unity for testing. The fact that more than one person is getting this should be a red flag
     
  42. pahe

    pahe

    Joined:
    May 10, 2011
    Posts:
    543
    We uploaded a bug report for it and it has been confirmed. Additionally, I told some guys at the Unite Europe about it and they confirmed that there are problems in 5.6 which they will investigate. The test project should help them.
     
  43. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    4,467
    Thank you. And I sent the team my entire project so far so they can test it. This issue only happens if I bake my scene using the prefab script for lightmaps. I had to do this because I use UFE and it uses prefabs for its level assets. So hopefully there is a fix
     
  44. B2F

    B2F

    Joined:
    Jul 10, 2013
    Posts:
    23
    So, it seems to be working for me other than the fact that when I bake the lighting on the prefab it seems to lose quality. See below screenshots.


    Before baking with one directional light on: before.jpg


    After baking with lights off:
    after.jpg

    Any idea what could be causing the quality loss? The lightmap parameters is set to "Default-HighResolution"
     
  45. tripknotix

    tripknotix

    Joined:
    Apr 21, 2011
    Posts:
    744
    just wanted everyone to know, i just successfully tested with 2017.1.0f1, the script that i posted before about a year ago and a half ago. its great to see its still being modified and used, ofcourse the original came from this forum thread, i only added to it.

    The test was built to WebGL 2.0 and works in chrome. Hopefully it still also works on android.
    if you want to see it, i got it working on the "Paradise City" map, the rest arent updated for it.
    http://realdefinition.net/play/
     
  46. pahe

    pahe

    Joined:
    May 10, 2011
    Posts:
    543
    @B2F Well, I can hardly see those shadows and wouldn't say the two screenshots look the same (as I would expect if everything is working correctly). You're sure the restoration of lightmap textures is working correctly for you?
     
  47. buttmatrix

    buttmatrix

    Joined:
    Mar 23, 2015
    Posts:
    609
    I̶s̶ ̶i̶t̶ ̶c̶o̶n̶f̶i̶r̶m̶e̶d̶ ̶t̶h̶a̶t̶ ̶t̶h̶e̶r̶e̶ ̶i̶s̶ ̶n̶o̶ ̶c̶u̶r̶r̶e̶n̶t̶ ̶s̶o̶l̶u̶t̶i̶o̶n̶ ̶f̶o̶r̶ ̶b̶a̶k̶i̶n̶g̶ ̶r̶e̶f̶l̶e̶c̶t̶i̶o̶n̶ ̶p̶r̶o̶b̶e̶ ̶d̶a̶t̶a̶ ̶i̶n̶t̶o̶ ̶p̶r̶e̶f̶a̶b̶s̶ ̶a̶s̶ ̶w̶e̶l̶l̶?̶

    EDIT: set reflection probe to 'custom' (thank you @KRGraphics)
     
    Last edited: Jul 25, 2017
    cLick1338 and chrismarch like this.
  48. tripknotix

    tripknotix

    Joined:
    Apr 21, 2011
    Posts:
    744
    @B2F i have the same issue, whats missing is that without real times lights your not getting the the bump map raised look of your rocks, and your not getting the specular look of those rocks either.
    So you're not getting bump or spec.
     
  49. bigdaddio

    bigdaddio

    Joined:
    May 18, 2009
    Posts:
    220
    No dice for me, I just try with 2017 and I get an error, Null object on line 237 file: PrefabLightmapData.cs
    I got the same error with unity 5.6
     
  50. unitymatrix

    unitymatrix

    Joined:
    Dec 29, 2009
    Posts:
    120
    in 2017.1.0, I do everything what above said, and try every script above,while the result is that when I rebuild the lightmap and set the prefab, only black and white.
    in lightmap setting windows,I could see the light texture,when I drag the lighting data file onto global maps,everything shows correct. while I saw that lightingdata.asset is just a editor file, if I want to run it in runtime,could't add it.

    normally I notice one question that, when I generate lightmap, the lightmapDir always to be null,anything wrong?
    even I run the demo preject,I need to drag the lightmapDir file to lightmap2 manually.

    Code (CSharp):
    1. #if UNITY_EDITOR
    2. using UnityEditor;
    3. #endif
    4. using UnityEngine;
    5. using System.Collections.Generic;
    6. using System.Linq;
    7.  
    8. public class PrefabLightmapData : MonoBehaviour
    9. {
    10.     [System.Serializable]
    11.     struct RendererInfo
    12.     {
    13.         public List<Renderer> renderer;
    14.         public int lightmapIndex;
    15.         public Vector4 lightmapOffsetScale;
    16.     }
    17.  
    18.     [SerializeField]
    19.     List<RendererInfo> m_RendererInfo;
    20.     [SerializeField]
    21.     Texture2D[] m_Lightmaps;
    22.     [SerializeField]
    23.     Texture2D[] m_Lightmaps2;
    24.  
    25.     const string LIGHTMAP_RESOURCE_PATH = "Assets/Resources/Lightmaps/";
    26.  
    27.     [System.Serializable]
    28.     struct Texture2D_Remap
    29.     {
    30.         public int originalLightmapIndex;
    31.         public Texture2D originalLightmap;
    32.         public Texture2D lightmap;
    33.         public Texture2D lightmap2;
    34.     }
    35.  
    36.     static List<Texture2D_Remap> sceneLightmaps = new List<Texture2D_Remap>();
    37.  
    38.     void Awake()
    39.     {
    40.         ApplyLightmaps(m_RendererInfo, m_Lightmaps, m_Lightmaps2);
    41.     }
    42.  
    43.     static void ApplyLightmaps(List<RendererInfo> rendererInfo, Texture2D[] lightmaps, Texture2D[] lightmaps2)
    44.     {
    45.         bool existsAlready = false;
    46.         int counter = 0;
    47.         int[] lightmapArrayOffsetIndex;
    48.  
    49.         if (rendererInfo == null || rendererInfo.Count == 0)
    50.             return;
    51.  
    52.         var settingslightmaps = LightmapSettings.lightmaps;
    53.         var combinedLightmaps = new List<LightmapData>();
    54.         lightmapArrayOffsetIndex = new int[lightmaps.Length];
    55.  
    56.         for (int i = 0; i < lightmaps.Length; i++)
    57.         {
    58.             existsAlready = false;
    59.             for (int j = 0; j < settingslightmaps.Length; j++)
    60.             {
    61.                 if (lightmaps[i] == settingslightmaps[j].lightmapColor)
    62.                 {
    63.                     lightmapArrayOffsetIndex[i] = j;
    64.                     existsAlready = true;
    65.                 }
    66.             }
    67.  
    68.             if (!existsAlready)
    69.             {
    70.                 lightmapArrayOffsetIndex[i] = counter + settingslightmaps.Length;
    71.                 var newLightmapData = new LightmapData();
    72.                 newLightmapData.lightmapColor = lightmaps[i];
    73.                 newLightmapData.lightmapDir = lightmaps2[i];
    74.                 combinedLightmaps.Add(newLightmapData);
    75.                 ++counter;
    76.             }
    77.         }
    78.  
    79.         var combinedLightmaps2 = new LightmapData[settingslightmaps.Length + combinedLightmaps.Count];
    80.         settingslightmaps.CopyTo(combinedLightmaps2, 0);
    81.  
    82.         if (counter > 0)
    83.         {
    84.             for (int i = 0; i < combinedLightmaps.Count; i++)
    85.             {
    86.                 combinedLightmaps2[i + settingslightmaps.Length] = new LightmapData();
    87.                 combinedLightmaps2[i + settingslightmaps.Length].lightmapColor = combinedLightmaps[i].lightmapColor;
    88.                 combinedLightmaps2[i + settingslightmaps.Length].lightmapDir = combinedLightmaps[i].lightmapDir;
    89.             }
    90.         }
    91.  
    92.         ApplyRendererInfo(rendererInfo, lightmapArrayOffsetIndex);
    93.  
    94.         LightmapSettings.lightmaps = combinedLightmaps2;
    95.     }
    96.  
    97.     static void ApplyRendererInfo(List<RendererInfo> infos, int[] arrayOffsetIndex)
    98.     {
    99.         for (int i = 0; i < infos.Count; i++)
    100.         {
    101.             var info = infos[i];
    102.             foreach (Renderer rer in info.renderer)
    103.             {
    104.                 rer.lightmapIndex = arrayOffsetIndex[info.lightmapIndex];
    105.                 rer.lightmapScaleOffset = info.lightmapOffsetScale;
    106.             }
    107.         }
    108.     }
    109.  
    110. #if UNITY_EDITOR
    111.     [MenuItem("Assets/Assign lightmaps to LOD")]
    112.     static void UseMeBeforeUpdatint()
    113.     {
    114.         PrefabLightmapData[] prefabs = FindObjectsOfType<PrefabLightmapData>();
    115.  
    116.         foreach (var instance in prefabs)
    117.         {
    118.             List<RendererInfo> tempListOfRender = instance.m_RendererInfo;
    119.  
    120.             foreach (RendererInfo ren in tempListOfRender)
    121.             {
    122.                 foreach (Renderer re in ren.renderer.ToList())
    123.                 {
    124.                     Transform myParentForSib = re.transform.parent;
    125.  
    126.                     foreach (var chil in myParentForSib.GetComponentsInChildren<Transform>())
    127.                     {
    128.                         if (chil != ren.renderer[0].transform)
    129.                         {
    130.                             if (chil.gameObject.name.Contains("LOD"))
    131.                             {
    132.                                 ren.renderer.Add(chil.GetComponent<MeshRenderer>());
    133.                             }
    134.                         }
    135.                     }
    136.                 }
    137.             }
    138.         }
    139.     }
    140.  
    141.     [MenuItem("Assets/Update Scene with Prefab Lightmaps")]
    142.     static void UpdateLightmaps()
    143.     {
    144.         PrefabLightmapData[] prefabs = FindObjectsOfType<PrefabLightmapData>();
    145.  
    146.         foreach (var instance in prefabs)
    147.         {
    148.             ApplyLightmaps(instance.m_RendererInfo, instance.m_Lightmaps, instance.m_Lightmaps2);
    149.         }
    150.  
    151.         Debug.Log("Prefab lightmaps updated");
    152.     }
    153.  
    154.     [MenuItem("Assets/Bake Prefab Lightmaps")]
    155.     static void GenerateLightmapInfo()
    156.     {
    157.         Debug.ClearDeveloperConsole();
    158.  
    159.         if (Lightmapping.giWorkflowMode != Lightmapping.GIWorkflowMode.OnDemand)
    160.         {
    161.             Debug.LogError("ExtractLightmapData requires that you have baked you lightmaps and Auto mode is disabled.");
    162.             return;
    163.         }
    164.  
    165.         Lightmapping.Bake();
    166.  
    167.         sceneLightmaps = new List<Texture2D_Remap>();
    168.  
    169.         var scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
    170.         var resourcePath = LIGHTMAP_RESOURCE_PATH + scene.name;
    171.         var scenePath = System.IO.Path.GetDirectoryName(scene.path) + "/" + scene.name + "/";
    172.  
    173.         PrefabLightmapData[] prefabs = FindObjectsOfType<PrefabLightmapData>();
    174.  
    175.         foreach (var instance in prefabs)
    176.         {
    177.             var gameObject = instance.gameObject;
    178.             var rendererInfos = new List<RendererInfo>();
    179.             var lightmaps = new List<Texture2D>();
    180.             var lightmaps2 = new List<Texture2D>();
    181.             GenerateLightmapInfo(scenePath, resourcePath, gameObject, rendererInfos, lightmaps, lightmaps2);
    182.  
    183.             instance.m_RendererInfo = rendererInfos;
    184.             instance.m_Lightmaps = lightmaps.ToArray();
    185.             instance.m_Lightmaps2 = lightmaps2.ToArray();
    186.  
    187.             var targetPrefab = PrefabUtility.GetPrefabParent(gameObject) as GameObject;
    188.             if (targetPrefab != null)
    189.             {
    190.                 //Prefab
    191.                 PrefabUtility.ReplacePrefab(gameObject, targetPrefab);
    192.             }
    193.  
    194.             ApplyLightmaps(instance.m_RendererInfo, instance.m_Lightmaps, instance.m_Lightmaps2);
    195.         }
    196.  
    197.         Debug.Log("Update to prefab lightmaps finished");
    198.     }
    199.  
    200.     static void GenerateLightmapInfo(string scenePath, string resourcePath, GameObject root, List<RendererInfo> rendererInfos, List<Texture2D> lightmaps, List<Texture2D> lightmaps2)
    201.     {
    202.         var renderers = root.GetComponentsInChildren<MeshRenderer>();
    203.         foreach (MeshRenderer renderer in renderers)
    204.         {
    205.             if (renderer.lightmapIndex != -1 && renderer.enabled)
    206.             {
    207.                 RendererInfo info = new RendererInfo();
    208.  
    209.                 info.renderer = new List<Renderer>();
    210.                 info.renderer.Add(renderer);
    211.                 info.lightmapOffsetScale = renderer.lightmapScaleOffset;
    212.  
    213.                 Texture2D lightmap = LightmapSettings.lightmaps[renderer.lightmapIndex].lightmapColor;
    214.                 Texture2D lightmap2 = LightmapSettings.lightmaps[renderer.lightmapIndex].lightmapDir;
    215.                 int sceneLightmapIndex = AddLightmap(scenePath, resourcePath, renderer.lightmapIndex, lightmap, lightmap2);
    216.  
    217.                 info.lightmapIndex = lightmaps.IndexOf(sceneLightmaps[sceneLightmapIndex].lightmap);
    218.                 if (info.lightmapIndex == -1)
    219.                 {
    220.                     info.lightmapIndex = lightmaps.Count;
    221.                     lightmaps.Add(sceneLightmaps[sceneLightmapIndex].lightmap);
    222.                     lightmaps2.Add(sceneLightmaps[sceneLightmapIndex].lightmap2);
    223.                 }
    224.  
    225.                 rendererInfos.Add(info);
    226.             }
    227.         }
    228.     }
    229.  
    230.     static int AddLightmap(string scenePath, string resourcePath, int originalLightmapIndex, Texture2D lightmap, Texture2D lightmap2)
    231.     {
    232.         int newIndex = -1;
    233.  
    234.         for (int i = 0; i < sceneLightmaps.Count; i++)
    235.         {
    236.             if (sceneLightmaps[i].originalLightmapIndex == originalLightmapIndex)
    237.             {
    238.                 return i;
    239.             }
    240.         }
    241.  
    242.         if (newIndex == -1)
    243.         {
    244.             var lightmap_Remap = new Texture2D_Remap();
    245.             lightmap_Remap.originalLightmapIndex = originalLightmapIndex;
    246.             lightmap_Remap.originalLightmap = lightmap;
    247.  
    248.             var filename = scenePath + "Lightmap-" + originalLightmapIndex;
    249.  
    250.             lightmap_Remap.lightmap = GetLightmapAsset(filename + "_comp_light.exr", resourcePath + "_light", originalLightmapIndex, lightmap);
    251.             if (lightmap2 != null)
    252.             {
    253.                 lightmap_Remap.lightmap2 = GetLightmapAsset(filename + "_comp_dir.exr", resourcePath + "_dir", originalLightmapIndex, lightmap2);
    254.             }
    255.  
    256.             sceneLightmaps.Add(lightmap_Remap);
    257.             newIndex = sceneLightmaps.Count - 1;
    258.         }
    259.  
    260.         return newIndex;
    261.     }
    262.  
    263.     static Texture2D GetLightmapAsset(string filename, string resourcePath, int originalLightmapIndex, Texture2D lightmap)
    264.     {
    265.         AssetDatabase.ImportAsset(filename, ImportAssetOptions.ForceUpdate);
    266.         var importer = AssetImporter.GetAtPath(filename) as TextureImporter;
    267.         importer.isReadable = true;
    268.         AssetDatabase.ImportAsset(filename, ImportAssetOptions.ForceUpdate);
    269.  
    270.         var assetLightmap = AssetDatabase.LoadAssetAtPath<Texture2D>(filename);
    271.  
    272.         var assetPath = resourcePath + "-" + originalLightmapIndex + ".asset";
    273.         var newLightmap = Instantiate<Texture2D>(assetLightmap);
    274.  
    275.         AssetDatabase.CreateAsset(newLightmap, assetPath);
    276.  
    277.         newLightmap = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
    278.  
    279.         importer.isReadable = false;
    280.         AssetDatabase.ImportAsset(filename, ImportAssetOptions.ForceUpdate);
    281.  
    282.         return newLightmap;
    283.     }
    284. #endif
    285. }
     

    Attached Files:

    eventropy likes this.
Thread Status:
Not open for further replies.