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. pahe

    pahe

    Joined:
    May 10, 2011
    Posts:
    420
    Sounds like your lightmap textures are not in the assetbundle. If lightmap textures are missing, the models will be black.
     
  2. JonnyHilly

    JonnyHilly

    Joined:
    Sep 4, 2009
    Posts:
    734
    put all your lights under one master "lights" object , then after you light map your scene.... turn off the 'lights' object... if its light mapped ok, nothing with change when you turn off the lights... and the light mapping is good. If it gets darker... then something is wrong, maybe you didn't set all lights to be 'baked' setting.

    also I noticed on my script, the checkbox m_getLightmapArray always makes the array the right size, but does not always copy in the textures... it seems to work on one machine I have, and fail on another... I don't know why. Check the light map textures are there on the prefab, in the array (on the lightMapManger component) .... if it doesn't copy the textures in... you might have to manually drag them in (in the correct numbered order, from your scene's light map folder of textures. e.g. if you scene is called awesomeLevel, then the light map folder will be right next to it, of the same name. You;ll find the textures in there.

    also remember to turn on the ready_to_go checkbox, and click apply on the prefab, before bundling.

    I have tested the prefab and bundle, on mac, pc, iOS and Droid... downloaded from server, and in editor.
    hope this helps
     
    Last edited: May 12, 2016
  3. MatiasPi

    MatiasPi

    Joined:
    Jul 13, 2015
    Posts:
    6
    Hi. I hope someone can shed any light on this, because I'm seriously losing my mind. I'm using the extension that lets you use prefabbed lightmaps that was posted here. The problem is that when you build the lightmaps on an atlas size bigger than 256x256, the wrapping breaks down. This ONLY happens on Android, BTW. It works perfectly on my PC. Here's a screenshot.

    http://puu.sh/oUQiF/e74bdba668.jpg

    Here are the bake settings:

    http://puu.sh/oUQnd/291df6deab.png

    I repeat, it all works perfectly if I change the Atlas Size to 256. It breaks down if you use a higher Atlas Size.

    I think it has something to do with the lightmap Offset and Scale, combined with how textures are imported into Android. This problem also happens when I try to use the same lightmap information on more than 1 mesh. I tried this by setting the same values in the Prefab Lightmap Data component on a second GameObject, so that it shares the same lightmap with another. Again, this worked perfectly on PC, but when I export to Android, the same thing happens. This forces me to have duplicated lightmaps because I can't change the texture offset...

    I swear, I will send $5 through PayPal to whoever explains to me what is going on and how to fix it.
     
    Last edited: May 17, 2016
  4. JonnyHilly

    JonnyHilly

    Joined:
    Sep 4, 2009
    Posts:
    734
    I think that you need light map offset and scale values, per object/mesh in the scene. I don't think that you can copy values from one object to another. Looking at the scripts uploaded... either the original one, or my modified one... both scripts copy light map values on a per-object basis.
    One other thing comes to mind... If you are bundling your prefabs, you might need to make different bundles per platform/target... but not suer about that... otherwise, not sure about the 256 limit...
     
  5. MatiasPi

    MatiasPi

    Joined:
    Jul 13, 2015
    Posts:
    6
    My game will only run on Android, so I don't need to worry about different bundles...

    I just tested this again and it looks like it also breaks down if I change the "Scale in Lightmap" value over here, in the "Object" tab in the Lighting window:

    http://puu.sh/oUT9j/f18780f73a.png

    So I can only set it to 1, which takes a LOT of space in the file. If I reduce it, the same thing happens. I don't need that much detail. I could just leave it like that, but that would have disastrous consequences in terms of framerate, load times, and file size.
     
  6. FrigginTommyNoble

    FrigginTommyNoble

    Joined:
    May 8, 2015
    Posts:
    3
    Alright guys, I've read through the thread, which goes back more than 2 years, and it's just not really clear what to do. There are many different copies of scripts and projects in here with fixes for various minor/patch Unity versions. So I'm gonna lay out my issue, and I kindly hope someone can lay out the steps and reference the "canonical" scripts I should use. Apologies if this is tedious, but I just don't have the historical context to follow the suggestions here that apply to my particular issue.

    I have a space game. In order to spawn into a level, you must first choose a ship in a ship selection scene (Hangar). There are like 10 ships, and have materials which use Unity's standard shader in deferred mode (not legacy). Metallic PBR workflow (textures from Substance Painter/Designer).

    1. When you choose your ship in the "Hangar" scene, that triggers a load of the actual level.
    2. The ship you chose is then instantiated from prefab.
    3. Included in this ship as a child GO is a reflection probe, which is required for the textures to reflect properly.
    4. The scene is lit by:
      1. Ambient GI from the skymap
      2. A "top down" directional light
      3. A "bottom up" directional light
    5. When the ship is instantiated, it's not lit right, implying the reflection probe does not contain baked lightmap data.
    Ok. So my workflow when editing a ship is:
    1. Bring ship prefab into the level (in editor)
    2. Make changes
    3. Bake reflection probes from Lighting tab
    4. Apply changes to prefab
    Ship's cockpit looks pretty sweet, lit well, textures look (I guess, kinda) close enough to what I made in Substance.

    Now, I delete the ship instance in the editor, so I can let the ship spawn logic do its thing. When I mash play and spawn into the level, the light probe is clearly not doing its job, because the cockpit mats are all washed out and not reflecting lights properly.

    Can anyone lay out for me the basic steps here?

    I have tried attaching the "Bake Prefab Lightmaps" script to the root prefab object. No dice. There seems to be an editor script floating around but instead of just pulling in scripts from a couple of years and flipping bits to try and get lucky, I figured I'd ask here.

    Unity version 5.3.4
    Windows 7

    Thanks!

    Ship cockpit asset baked in scene editor (how it should look):




    Asset instantiated at runtime (how it most certainly should NOT look):

     
    Last edited: Jun 1, 2016
  7. pahe

    pahe

    Joined:
    May 10, 2011
    Posts:
    420
    Though I'm not sure if the scripts and the solution in general here in the thread works with reflection probes, have you checked if the lightmap textures are present during play? The main problem with lightmaps are currently, that the lightmaps baked by Unity are scene assets (you can see that in the Inspector View that they are in bold) and that scene assets are not put into prefabs.

    So what the script here actually is doing is: creating a copy of the Unity lightmaps, changed references on Renderers which used the Unity lightmaps to actually use the new copy (which is a project asset now) and save the prefab with the new references.

    That's the summary. If you think that that may be a solution for you, you can check if the lightmap textures are present at runtime. If they are missing, then you know now what the problem is.


    Hope that helps.
     
  8. FrigginTommyNoble

    FrigginTommyNoble

    Joined:
    May 8, 2015
    Posts:
    3
    That does help, thanks.

    I tried placing the reflection probes outside the actual ship prefab and baking the scene. This helped as reflections on the PBR textures looked good. So I don't need to bundle the lightmaps with a reflection probe local to the ship gameObject.

    However this creates a whole new problem which I'll create a new thread for: How do I deal with reflection probes in a very large scene (sphere with a radius of 2000 unity units)? My solution was to bake a reflection probe that moves with the ship, as a child object. But once I made the ship a prefab, and instantiate it on scene load, I lost the lightmap data. I still feel like the workaround here is the only option, I'm just not convinced it's a robust enough solution that's production-ready. I'd love to be shown why I'm wrong on that though.
     
  9. dreamerflyer

    dreamerflyer

    Joined:
    Jun 11, 2011
    Posts:
    904
    Got new problem ! prefab with lightmap not correct when load to different level! lm1.jpg lm2.png
     
  10. pahe

    pahe

    Joined:
    May 10, 2011
    Posts:
    420
    The lightmap settings are per scene. You would have to add them to the existing ones, if you don't unload the old scene.
     
  11. JonPQ

    JonPQ

    Joined:
    Aug 10, 2016
    Posts:
    70
    The script above should work between scenes, and even between projects... I have used it to bundle an asset in one unity project, then stream it from server and load into a different project successfully. Dont know if it works with reflection probes though.
     
  12. JonPQ

    JonPQ

    Joined:
    Aug 10, 2016
    Posts:
    70
    Random side effect... Unity squirts out a Warning message for every 'static' object the fix script runs on. (when it re-stores the saved offset and scale light-map values) This can be a lot of debug logs, and can slow app at init-time. But if you don't run the code the fix doesn't work. Is there any way around this ?
     
  13. Dragonhill

    Dragonhill

    Joined:
    Jun 2, 2010
    Posts:
    21
    Hi Guys, So i was able to get code running on stock unity geometry and it seamed to work fine with prefabs..

    now my big issue.. Probuilder... yup.. i like to use Probuilder and oh boy.. Houston, we have a problem. I have not contacted the maker yet but i'm pretty sure the geometry uv points are remapped and this basically fubars this code when it rys to apply the lightmaps to the geometry. Anyone else have these issues?

    ~D
     
  14. JonPQ

    JonPQ

    Joined:
    Aug 10, 2016
    Posts:
    70
    @FrigginTommyNoble... The 2 scripts I posted above... work on iOS PC droid and Mac (tested) as prefab loads or streamed bundles. in Unity 5.3 and 5.4 latest. You put the lightmapManager on the root object/prefab/lightmap scene. Follow the instructions in the script... and it should work as a loaded prefab into another scene. Note.. if you are trying to load it into another light-mapped scene... with different light maps.... well good luck with that.... IT doesn;t work to combine multiple different light map setups into one scene together. But it works to bake lightmaps into a prefab that you can load and instantiate.
     
  15. JonPQ

    JonPQ

    Joined:
    Aug 10, 2016
    Posts:
    70
    Maybe you are bundling in PC mode, or mac, or iOS, then loading to Android ? Bundle assets might be in different format for different platforms ?
     
  16. Mr_Dan_O

    Mr_Dan_O

    Joined:
    Oct 12, 2013
    Posts:
    346
    I have a scene with 510 terrains which if player gets near them, they will get "enabled" and if player goes far away they will be "disabled" so it means they are loaded first in the memory then they get disabled if they are too far. The problem is I can't apply lightmap to them. So I just don't know how to bake lightmap for these 510 terrains in the scene.

    Is it possible to bake them in other scenes individually and merge them into the main scene? Please help, Thanks for reading.
     
  17. StaggartCreations

    StaggartCreations

    Joined:
    Feb 18, 2015
    Posts:
    809
    I'm facing the same issue. Before you load your lightmaps, you have to set the Directional Mode to Non-Directional through script, even though you already set it correctly in the scene:

    Code (CSharp):
    1.  LightmapSettings.lightmapsMode = LightmapsMode.NonDirectional;
    Problem now is though, it only works in the editor... did support for Non-Directional lighting get borked in 5.4?
     
    alexmeister92 likes this.
  18. tripknotix

    tripknotix

    Joined:
    Apr 21, 2011
    Posts:
    737
    heya jonpq, im getting lost in here, i editted this script years ago, but which script exactly are you talking about works in 5.4?
     
  19. hwizard

    hwizard

    Joined:
    Jun 30, 2016
    Posts:
    3

    YOU SAVED ME :) THANKS
     
  20. idurvesh

    idurvesh

    Joined:
    Jun 9, 2014
    Posts:
    473
    Glad :)
     
  21. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    3,975
    This is good... I just found this since I needed to solve this particular issues. In my tests, I am not using lights but emissive objects... and it also doesn't seem to work with realtime lights or precomputed GI.


    Edit: This works PERFECTLY... tested this in my small scene... put a dummy light in there set to baked... doesn't work with reatime GI (which I rather use since the baked GI is not great tbh)
     
    Last edited: Sep 24, 2016
    idurvesh likes this.
  22. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    3,975
    I do have a question... when I set up the prefabs for GI baking, the reflection probe is not in the bake... does your script include reflection probes as well...
     
  23. idurvesh

    idurvesh

    Joined:
    Jun 9, 2014
    Posts:
    473
    I do not remember correctly in moment.....Please read replays on page number 4 5 ...You might get good answer for it there...
     
  24. ccoltharp

    ccoltharp

    Joined:
    Apr 1, 2015
    Posts:
    5
    Hey- I've tried this script and the one idurvesh made, but I'm still getting lightmap errors on play. The duplicated prefab in the editor is a little darker, but in play mode, the duplicated prefab is completely bonkers. The objects are using the lightmap like a texture for some reason. Any ideas?
     

    Attached Files:

    • lb01.jpg
      lb01.jpg
      File size:
      73.6 KB
      Views:
      580
  25. www_3dart_es

    www_3dart_es

    Joined:
    May 24, 2013
    Posts:
    201
    Almost a year and a half and no adequate solution to work properly?
     
  26. www_3dart_es

    www_3dart_es

    Joined:
    May 24, 2013
    Posts:
    201
    You need a solution for this because if you have the same scenario for multiple scenes you are wasting a lot of memory in lightmaps. It is a disaster in Android games....
     
  27. www_3dart_es

    www_3dart_es

    Joined:
    May 24, 2013
    Posts:
    201
    Well, in page 5 I FOUND THE SOLUTION. It must be in the first post of the Thread.

    I also found other Videotutorial in HD (idurvesh did put a low resolution Video and we can´t read the text):


    idurvesh, I got my proyect to work with your Script, thanks you very much.

    I found a bug, that when I press the "Bake prefab lightmap" button, it creates other Script component in the Empty of the prefab. If later I make more Bakes it creates more scripts on it.

    Regards and thanks you again.
     
    idurvesh likes this.
  28. www_3dart_es

    www_3dart_es

    Joined:
    May 24, 2013
    Posts:
    201
    In editor it works perfectly but when I export it to Android, and change to the second level (the one with the prefab scenary) some objects seems that have incorrect lightmap texturing. It is a bug in Unity, or with the Script?
    Fail1.png Fail2.png Fail3.png
     
  29. www_3dart_es

    www_3dart_es

    Joined:
    May 24, 2013
    Posts:
    201
    In the first Scene it looks perfectly on Android... :(
     
  30. idurvesh

    idurvesh

    Joined:
    Jun 9, 2014
    Posts:
    473
    Try running second scen directly and see if it solves the problem

    Glad someone did HD video over it ^_^
     
    www_3dart_es likes this.
  31. www_3dart_es

    www_3dart_es

    Joined:
    May 24, 2013
    Posts:
    201
    I just tried it but it continues equal.
     
  32. www_3dart_es

    www_3dart_es

    Joined:
    May 24, 2013
    Posts:
    201
    I am on Unity 5.4.1p1 and I was waiting for the upcoming Unity 5.5 (it is in Beta10 now). Maybe this is an Unity bug?. Or is related to your Script?. I am stucked now and I can´t continue the game with this graphic problem...(I tested on other Android device and have the same problem) :(

    Thanks in advance.
     
  33. idurvesh

    idurvesh

    Joined:
    Jun 9, 2014
    Posts:
    473
    It is not actually my work, it is excellent work of @Centripetal , when we were having Unity bug (You can read about it from page 2) .I just added LOD groups and GUI layer above it.

    Fortunately after bug case to Unity, later version of Unity did solve that bug.

    Now,I believe original script by @Joachim_Ante do work.

    Check if that solves your problem, here is modified version of that script by @WillemKokke ,
    https://forum.unity3d.com/threads/problems-with-instantiating-baked-prefabs.324514/#post-2229465

    If above do not solve your problem then please make demo project and send it here or via PM.
     
  34. www_3dart_es

    www_3dart_es

    Joined:
    May 24, 2013
    Posts:
    201
    I used the script but it throw errors, I must to delete all your scripts from your package?

    Anyway, I read here https://forum.unity3d.com/threads/problems-with-instantiating-baked-prefabs.324514/#post-2208501
    that setting off Static batching should work and I did try it and now it looks perfect!! (using your package)

    Thanks for your interest!! Regards!!
     
    idurvesh likes this.
  35. congtrungvnit

    congtrungvnit

    Joined:
    Jul 18, 2016
    Posts:
    14
    It works but seems a bit strange in my case. In my case, I have a scene with some rooms, the rooms are prefab and light mapped, each room prefab has a light probe group. The problem is that the light probe group of each room prefabs seem to be not aligned correctly when I initialize those prefabs. So my dynamic objects are not illuminated correctly. Anyone has solved similar problem please help me.
     
    Last edited: Nov 14, 2016
    idurvesh likes this.
  36. Astiolo

    Astiolo

    Joined:
    Dec 18, 2014
    Posts:
    27
    Thanks everyone who has contributed to this. It's pretty bad form by the Unity devs to leave this sort of feature building up to the community.

    I am having an issue though where I have to apply the lightmaps before building or they won't be there in the build. Thankfully I only have one scene at the moment so I can do that, but is there a way to fix it so I don't have to remember it every time I want to test a build?

    I tried the updated version but there were bugs for me on Unity 5.4.2. What version should it be working for?
     
  37. idurvesh

    idurvesh

    Joined:
    Jun 9, 2014
    Posts:
    473
    I believe you have to build lightmaps once > save those onto "Resources" folder so they always get included in build.
    Which script are you referring to? The script on first page of this thread work fine for me in 5.4.2.
     
  38. Astiolo

    Astiolo

    Joined:
    Dec 18, 2014
    Posts:
    27
    The version of the script that I'm using already saves them into the Resouces folder, but it's not solving the problem.

    I quoted the post with the version that I was referring to. It's the updated package that you uploaded on post number 206 (https://forum.unity3d.com/threads/p...ting-baked-prefabs.324514/page-5#post-2519284).
     
    KyleStank likes this.
  39. Astiolo

    Astiolo

    Joined:
    Dec 18, 2014
    Posts:
    27
    Looks like I must have been doing something wrong. I'm not exactly sure what, because the Resources folder was one of the first things I looked at and I can't think of anything else I've changed related to the light mapping. But, thankfully it's just not a problem anymore.
     
  40. KyleStank

    KyleStank

    Joined:
    Feb 9, 2014
    Posts:
    204
    Really Unity? I had to dig through to forum like this to find an answer that was already in Unity 4. This is disappointing, as this script should just be included in Unity.
     
    idurvesh likes this.
  41. yang-yu

    yang-yu

    Joined:
    Mar 8, 2013
    Posts:
    21
    @Joachim_Ante
    It's worked with single scene.
    Is there any solution for multi scene baked lightmap, and runtime set lightmap index?
    I'm building a huge world with streaming, can't use LoadSceneMode.Additive,
    because the limit of the memory and streaming experience
     
  42. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    3,975
    Is this working in 5.5? This is ridiculous now and I have scenes that require me to use prefabs for the levels and the script provided isn't doing anything. It is saving the lightmap in the folder, but it will not show up...
     
  43. Astiolo

    Astiolo

    Joined:
    Dec 18, 2014
    Posts:
    27
    It's working in 5.5 for me, no different to the older version. But I do agree that it's ridiculous that Unity doesn't have this as an inbuilt feature.

    If I'm not mistaken, there is an issue if the lightmaps aren't loaded in early enough (i.e in Start instead of Awake). Which is a little annoying for me because I would like to instantiate some lightmapped prefabs at runtime. But I wonder if that's the same problem with LoadSceneMode.Additive?
     
  44. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    3,975
    Then why am I NOT GETTING ANY LIGHTMAPS?!!!

    Look at this! I have the script and folders set correctly and everything
     

    Attached Files:

    Last edited: Dec 21, 2016
  45. Astiolo

    Astiolo

    Joined:
    Dec 18, 2014
    Posts:
    27
    It looks like the prefab doesn't have any lightmap information stored on it. Something must be going wrong somewhere in the preparation. You need to have another scene where you create the lightmap, then bake it to the prefab. At this point make sure the prefab is referencing the lightmap file and lightmap coordinates.

    Make sure you also have the objects set to lightmap static but not batching static in the scene where you are applying it.
     
  46. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    3,975
    I saw the culprit... had to set the lightmap type to non directional...
     
  47. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    3,975
    I also missed the step where I had to enable lightmap static on the prefab parent... weird but it works now.
     
  48. inthemilkywat

    inthemilkywat

    Joined:
    Dec 29, 2013
    Posts:
    54
    If my scene doesn't already have a lightmap data, do I need to create one? I am randomly generating a dungeon at runtime from prefabs so there is no lightmap data in the scene to combine with.

    Edit: oh nvm, i can just bake the scene without any lights first.
     
    Last edited: Dec 24, 2016
  49. Hunduan2015

    Hunduan2015

    Joined:
    Jan 13, 2017
    Posts:
    2
    hii!
    when i Build whold Scene into a AssetBundle. The problem is the Terrain lightmap is missing! i'm not used prefab. But if i rebake that scene on my PC, when buildPlayer the scene lightmap is run corrently! the assetbundle is the same before Built, is not changed. editor always OK!
    anyone can help me ???

    PS: UNITY5.3.4f1
     

    Attached Files:

    • 1.png
      1.png
      File size:
      278 KB
      Views:
      577
    • 2.png
      2.png
      File size:
      319.1 KB
      Views:
      494
    • 3.png
      3.png
      File size:
      315 KB
      Views:
      498
    Last edited: Jan 13, 2017
  50. Astiolo

    Astiolo

    Joined:
    Dec 18, 2014
    Posts:
    27
    Just thought I should share a problem I had and how I solved it. I was having trouble additively loading a scene with prefab lightmaps. The original scene didn't have any lightmapping and when loading the other scene, the prefab lightmaps would be added before the base one from that scene. I believe that was causing the lightmaps to be referenced incorrectly, it wasn't working anyway.

    Eventually I solved it by making it wait until the end of the frame to apply the lightmaps, that way the ones built into the scene would already be applied. To achieve this, you can add in the command: yield return new WaitForEndOfFrame();

    Obviously it must be a coroutine for that to work.

    I was also using nondirectional lightmaps and was getting errors when the code was trying to apply the directional ones. So I added in a static boolean to set weather you want to use directional maps or not (needs to be edited in the script if you want to change it). The last change I made was to update the references of lightmapNear and lightmapFar to lightmapLight and lightmapDir to match the new naming convention in Unity 5.5.

    Here is the full code as I am using it:

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