Giter Site home page Giter Site logo

ayfel / prefablightmapping Goto Github PK

View Code? Open in Web Editor NEW
614.0 614.0 88.0 30 KB

Script for saving lightmapping data to prefabs. Used through the Assets tab in Unity. Place your prefbas in the scene with this script at the root. Set up your lighting and in the editor go to Assets->Bake Prefab Lightmaps. After is processed you can now spawn your prefabs in different scenes and they will use the lightmapping from the original scene.

C# 100.00%

prefablightmapping's People

Contributors

ayfel avatar parixit2411 avatar telroshan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prefablightmapping's Issues

License

Hello, I can't find anything about license in this repository so could you tell me can I use this script in my personal or commercial projects?

If this is not a problem for you I suggest to add a clear license like CC0 to Readme.md for future users.

Nested prefabs

That's great. Thanks for sharing.

Is this script compatible with 2018.3 and nested prefabs?

Does not work with Probuilder

First of all, thanks for this awesome script. It works like a charm with most models.

Unfortunately there seems to be a problem with meshes created with Probuilder. When creating a model with probuilder inside Unity and using it as a prefab, the lightmaps seem to be misplaced. Also when using a complex prefab with Probuilder elements and normal elements, all normal elements (thanks to your script) have the correct lighting. All Probuilder elements look messed up. Therefore I think this is a problem of Probuilder.

I will recreate the affected elements outside of Unity now. Just leaving this as a comment so others won't have to search forever.

Lightmaps not working in build with Generated Lightmap UV's

I don't know if it's a bug in Unity or not. But when I have generated lightmap UV's in mesh lightmaps are not working in build.
image

I'm instantiating prefab in runtime and have disabled static bathing. I also prepared a sample project. It is possible that Unity generated different UV's in build than in Editor?

I'm using Unity 2020.3.17 and URP
PrefabLightmapping.zip

Lightmaps don't apply correctly

I'm using this script to have baked lighting on prefabs for procedural levels, and I have it working, but for some reason the lightmaps don't apply correctly until I move the object in the editor, and then use ctrl+z to move it back to it's original position.

Here's what they look like after instantiation
BEFORE MOVE

And here's what they look like after moving then undoing the move in editor
AFTER MOVE

I've tried including the prefabs in the scene small and out of the way but the issue still persists.

Lightmaps load problem

Hi first of all, thanks for this script is great :) , but i've got a problem. When i spawn prefab with baked lightmaps from pool sometimes they don't wont to load like on the screen below. This is the same prefab.

Unity_LpuR2ZTyq9

Save the info in script to another file

Can you make the attached script on root prefab save info in another file?(something like txt)

This
image
We really need this and i can explain why if you want.

Lightmaps are messed up in build

https://imgur.com/a/qXn4AOo

We are using HDRP 2019.3.10f1

Here's how ligtmaps look in build and ran in unity editor. We're aware that there was same issue a while ago but the solution doesn't work for us.
Do you have any idea why is it happening, and how to solve it?

Lightmap broken on android and URP

When running on an Android device the result is not as expected.
When using LightmapPrefabData the results are as below.
Baked lightmapping on static objects without LightmapPrefabData works as expected.

Editor in Play mode
image

Running on Android device
image

It shows black on Android devices.

Works perfect on Windows and was amazed by the ease provided.

My steps for repro:
I have two independent Android Unity projects. I am exporting from one project and importing in other. Both projects contain the lightmapping script. Works on the Windows device[tested only in Editor with build settings set to Android ] but after making a build for Android it shows black on the Android device, only the skybox is colored, all the baked static items are black.

I have made sure via runtime Hierarchy that the script is loading correctly and that all the parameters are set correctly.
Tested on all three Graphics Api : Opengl3, 2 & Vulkan. Got same results on the Android device.
Using Unity 2019.4.10 (LTS).

Please see the attached images.

[ Lucky to find this repo after spending almost 6+ hours on this issue. Thank you for the great work! ]

image
WhatsApp Image 2020-09-21 at 7 33 51 PM

Not working correctly on Prefab Variants

First of all very cool script. I have a problem using this with prefab variants, if I bake the light on a prefab variant he is copying all meshes to the parent prefab.

I made a quickfix but I'm not sure about it. I commented out everything and only left the stuff in the else branch, it seems to work.

if (targetPrefab != null) {
                GameObject root = PrefabUtility.GetOutermostPrefabInstanceRoot(instance.gameObject); // 根结点
                //如果当前预制体是是某个嵌套预制体的一部分(IsPartOfPrefabInstance)
                if (root != null) {
                    GameObject rootPrefab = PrefabUtility.GetCorrespondingObjectFromSource(instance.gameObject);
                    string rootPath = AssetDatabase.GetAssetPath(rootPrefab);
                    //打开根部预制体
                    PrefabUtility.UnpackPrefabInstanceAndReturnNewOutermostRoots(root, PrefabUnpackMode.OutermostRoot);
                    try {
                        //Apply各个子预制体的改变
                        PrefabUtility.ApplyPrefabInstance(instance.gameObject, InteractionMode.AutomatedAction);
                    } catch { } finally {
                        //重新更新根预制体
                        PrefabUtility.SaveAsPrefabAssetAndConnect(root, rootPath, InteractionMode.AutomatedAction);
                    }
                } else {
                    PrefabUtility.ApplyPrefabInstance(instance.gameObject, InteractionMode.AutomatedAction);
                }
            }

Not working

  1. Create new project: 2019 + Uwrp (Old 3D has the same issue)
  2. Create scene, set to subtractive lighting.
  3. Create plane+cube, add script, make prefab out of them.
  4. Bake lightmap, bake prefab from menu.
  5. Create new scene, put prefab in it.
  6. Hit play.
    The lightmaps on the prefabs kind of get loaded, but they have heavy black/white/pink artifacts. The whole prefab is also affected by realtime lighting.
    Does it not work or am I doing something wrong?

lightmap

Light probes?

Hello

I'm using this script for prefab lightmapping, and it works really well.
But one thing that I noticed is that light probes don't seem to work in the instantiated prefab instances. However, in the scene where I bake my prefab, they work very well.

Is this a known issue/limitation? Any way to get them working?

Detail Map in standard Shader stripped in Builds 2019.3

I have an older project on 2019.3 I'm trying to get to work with this script.

This works fine while in editor, but in the built game, some nested prefabs using the unity Standard shader that are already baked using realtime GI in the scene show up as unlit as if the lightmap is not applied, both in the prefab being spawned and in the scene that exists (it is the same inner prefab).

This happens whether the prefab was in the scene or spawned (it will go dark as soon as I spawn it). It happens whether or not the objects in the prefab are flagged as static or not. And it happens whether or not I strip all shaders or not (set to custom with everything checked, etc) in settings.

The only thing I notice is the textures are not under resource/*. I'm not sure if they need to be. The other level with a reference to this prefab is not included with the build. I will check just including that to see.

Compilation Error on new project

Hi Ayfel, there are these two errors thrown in Unity Console, I will appreciate if you can offer a fix, thanks. Because I am a designer not good at coding, I couldn't fix myself.

Assets/Scripts/PrefabLightmapData.cs(72,107): error CS1525: Unexpected symbol `,', expecting `('
Assets/Scripts/PrefabLightmapData.cs(73,105): error CS1525: Unexpected symbol `,', expecting `('

new feat: add script to Empty Game Object instead of object ?

Hi,
I would like to know if the features below would be possible:
Can we imagine to add your script to an Empty Game Object and then specify the concerned baked object and maps?
In our project we are using asset bundle for 3D object but also to save "settings" and load them depending of the needs.
Having the same with your script would unlock the ability to have multiple baked maps on the same object.
What do you think or do you have any clue how to manage multiple baked maps ?
Thanks for your reply and your great sript.

LightMaps are Misplaced

In my project my lightmap are working fine if i am instantiating them as a prefab
(Image1: Instantiating as a prefab)
image

but when i am building the asset bundle of that prefab and try load that asset then the lightmaps are getting misplaced:
(Image 2: Instantiate from asset bundle of above prefab)
image

can anyone suggest me whats the issue
(i am using unity 2020.3.4f1 URP)

Clarification of Light Probes

This stuff is a godsend for procedural devs but I would like some clarification on the light probes.

When you say "create a uniform light probe group in the scene you are going to instantiate prefabs at" do the light probe groups really have to be perfectly uniform?

Also, since they have to already be in the scene itself, and not within the prefabs, how would we fine tune where they end up once the prefabs instantiate (i.e. preventing them from being in walls, getting them to be in crucial areas where the light changes substantially)?

Having realtime shadows on the baked prefabs

Hi, I made the bake on some prefabs, and now when I try them in a new scene they are affected by the directional light as if they have not been baked. I tried changing the layer of the meshes inside the prefabs so that I set the directional light in the scene to that the culling mask don't affect them. It solves the "double" lighting issue, but now shadows are not casted onto them (which makes sense...) I suppose there must be a way of making the prefabs behave as already baked.

URP AssetBundle lighting corrupted

Hi,

I've been reading some threads in Unity Answers forums (Thread in Unity Answers Forum) and some issues here but I cannot fix the corrupted result of my lighting after using PrefabLightmapping scripts in a prefab built into an AssetBundle and uploaded to a server.

The thing is: I've set as "Custom" the "Lightmaps Modes" in "Shader stripping" and clicked on the "Import From Current Scene" button. After that, I set a root prefab containing all the meshes from that scene and click on "Baked Prefab Lightamps" just as you do in the README file. Once I do that, the prefab is shown properly, but if I build an AssetBundle with that prefab, download it from a server and instantiate that prefab into a different project (an identical copy of the project to avoid errors of having different lighting settings), the lights appear corrupted.

I have no idea from where the meshes come (I don't know if there's a way to check if the meshes were built in Probuilder or not).

I'm using:
URP
Unity 2020.3.27f1

This is one of the results.

Original:
prefablightmapping

After instantiate from the AssetBundle:
prefablightmapping_wrong

Any ideas about this?

Thanks!

Bake lighmap with consistent UV Layout

Is there a way to generate lighmaps with the same UV layout? Right now when I bake lightmap again, without any changes, it looks slightly different. I'm trying to swap lightmaps on runtime and I need to generate few lighmaps with the same UV layout.

Works in editor, but turns black in browser for WebGL

Hello! Love this script - it's perfect as we're assetbundling prefabs.
One thing though, it seems to work when we load the asset bundle in editor, but when we load in our web app, the textures turn black. Any idea what could be causing that? Thanks!

Inconsistent application of lightmaps on rotated prefabs instantiated by script

Thank you so much for your work on this. This is really great stuff. I am having an issue with the lightmaps sometimes not being applied to my prefabs (happens about 30% of the time).

I am trying to build an "infinite office space". I make prefab rooms, and then as the player traverses the rooms, more are generated on the fly, and old ones are destroyed. To generate the lightmaps, I have put each room in its own scene, and I then use your "Bake Prefab Lightmaps" option. This works, and populates the Prefab Lightmap Data on each prefab room. Within each room's scene, I can also drag in copies of that room, and the lighting works on each one.

For the actual "game", I Instantiate() the prefabs using a script. Most of the time, the lighting is correct, but sometimes, the lighting looks very strange. Do you have any ideas why this would be happening?

Here are some relevant images:
https://imgur.com/a/KBlkGAb

When I baked the lighting, I set everything in the prefab as Static. After baking, I tried making the prefabs NOT static. This did not fix the problem. I also tried keeping them static and had the same problem.

The inconsistency is very confusing to me. Any help would be amazing. Thank you so so much.

Does not cooperate with Postprocessing and Aura 2

Perhaps this is outside the scope of this project, but the results are significantly different between the editor scene, and the lightmapped prefab in another scene with an otherwise identical setup. The scene on the right is from the scene view during play mode, but the game view is equivalent.

Postprocessing is darker than it should be, lights are not taken into account somehow
Aura 2 light isn't working, producing strong spotlight halo effects.

Unfortunately, due to the size and complexity of my project I can't easily give you a repro case.

Post Processing from the Package Manager, version 2.1.7
Aura 2, version 2.1
https://assetstore.unity.com/detail/tools/particles-effects/aura-2-volumetric-lighting-fog-137148

SceneVsRuntimeResults

Lightmap changes when scene is changed.

Hello, im a beginner trying to make a procedural driving game. My road is being made at runtime so i needed your script for saving my lightning data. So i did;
1)Put my road prefabs on a scene with a baked light(streetlamp)
2)Baked prefab lightmaps from Assets/Bake Prefab Lightmaps
3)Built the game on android platform, with Baking scene first, playing scene second.
When i run the game on play mode, everything is fine. My baked data transfers to the second scene and there is no problem. But on android build it breaks.

This is the first scene where i baked the data, the normal lightmap should be like this so it is baked fine. When the button is pressed, i proceed to the second scene where the game is played.

And this is the second scene where the magic happens. The textures are partly black, partly lit.

I have post processing on the playing scene so i thought maybe it is the reason, but when i deactivated it nothing changes, still black textures. Been trying to fix this for almost a week. Any help would be amazing, thanks.

Light probes in Interior scenes

Hey, Thanks so much for this. It is a life saver so far.

Began playing with the light probes (massive thanks for getting that working!), but had an issue with using them in an interior scene. Since the light probes pick up every light within range, light from one room was contributing to the probes in adjacent rooms.

Got a workaround I think after a bit of experimenting. I'm fairly new to Unity so not sure if this is the best way to do it.

               int layerMask = ~LayerMask.GetMask("Furniture");
               for (int i = 0; i < probeCount; i++)
                {
                    if (!Physics.Linecast(probePositions[i], l.transform.position, layerMask))
                    {
                        SHAddPointLight(probePositions[i], l.transform.position, l.range, l.color, l.intensity, ref bakedProbes[i]);
                    }
                    else
                    {
                        SHAddPointLight(probePositions[i], l.transform.position, l.range, l.color, l.intensity * 0, ref bakedProbes[i]);
                    }
                }

Basically, this checks if the light probe has line of sight with the point light. Also added a layermask so it ignores the furniture in the rooms. This way, the script can check if there is a wall in the way of the point light, and if there is, it reduces the intensity of that point light to zero for the probe. Only lights within the same room will contribute to the probes.

Not noticed any major impact to performance and it looks like it works. Any issues with this solution do you think? Another issue I had was the light probes were too bright, so just divided intensity by 4 and that seems closer. Prob something to do with my lightmap being dark.

And is it possible to add spot lights and area lights maybe? :D

Many thanks again

"Index was outside the bounds of the array"

I'm getting the following error, Can you advise?

IndexOutOfRangeException: Index was outside the bounds of the array.
PrefabLightmapData.GenerateLightmapInfo (UnityEngine.GameObject root, System.Collections.Generic.List1[T] rendererInfos, System.Collections.Generic.List1[T] lightmaps, System.Collections.Generic.List1[T] lightmapsDir, System.Collections.Generic.List1[T] shadowMasks, System.Collections.Generic.List`1[T] lightsInfo) (at Assets/Scripts/PrefabLightmapData.cs:245)
PrefabLightmapData.GenerateLightmapInfo () (at Assets/Scripts/PrefabLightmapData.cs:182)

PrefabLightmapData (script) sets all material custom render queues to -1

As the titles states.

The scripts sets all the custom render queues of the materials on the child objects to -1.
This cause my materials to render improperly.

Normally opaque materials will render on queue/layer 2000 and transparent materials on queue/layer 3000.

Because they all get set to layer -1 the transparent materials dissapear.

Misaligned lightmaps when using BakeAsync()

My lightmaps are misaligned when using this script for baking. I use Unity 2020.1.12f and have some complicated and unoptimized geometry.

I think the reason is that the script uses BakeAsync() without waiting for the bake to complete. Instead it assigns the currently existing lightmaps immediatly. Or nothing if no lightmap existed.

However when starting the bake in Unity and after completion running the script without the BakeAsync() call everything is working fine and aligned correctly.

In any case, this script is a tremendous help. Thank you.

No feedback

When I clicked on Bake prefab from assets the editor just froze there was no visual feedback as to if the lights were being baked...were they?
Usually, it takes 15-20 mins to bake the same prefab, so should I just wait for 20 mins and hopefully it magically bakes and unfreezes? Or is there a problem?

(I know it's technically not an issue that I should open up but there was no other way to ask the question 😉)

Warning in 2020.1.2f1

Show this warning

Assets/PrefabLightmapData.cs(272,48): warning CS0618: 'LightmapEditorSettings.mixedBakeMode' is obsolete: 'LightmapEditorSettings.mixedBakeMode is obsolete, use Lightmapping.lightingSettings.mixedBakeMode instead. '

Lightmap working fine first time, but not applying on subsequent

Hello there.

I have a problem with baking a prefab and I don't know how to proceed.

I have added the script to a prefab with some models and terrains. When the baking process is over, you can see the effect on the terrain: the objects cast shadows in the terrain.

LHE - 01 - Baked shadows work perfectly

But if I remove the prefab from the scene and add it again, it should show the same lightmapping as before, but in this case, they are removed:
LHE - 02 - Removed and added again - Not showing baked shadows

If I play the game and instantiate that prefab in another scene (the purpose of the asset), the shadows are gone too.
LHE - 03 - Instantiated in realtime in another scene - Not showing baked shadows

What am I doing wrong? Thanks a lot for your time!!!

Does not appear to work?

Hello all,
I was able to get the script to generate the light maps, but when I load the prefabs in a different scene there is no visual change.
Is there a video somewhere showing the proper workflow?

@Ayfel: I was hoping to email or DM you but I couldn't find how to do that. The company I work for is working on a fairly large project that has an "Infrared" view and we think this might be the tool we need to simulate hot spots on our models. We would love to chat about the tool and possibly some minor consulting work.

Can't get baked lighting to work in a cloned prefab object

Hi there,

I have quite a simple set up, one prefab with one area light in it and some other prefabs inside it.

image

I've run the Assets->Bake Prefab Lightmaps, which generated the lightmaps on the right, which seems fine.

When I run my code, I'm instantiating a clone of RoomMedium1 next to it, but no lightmaps are applied to it

image

What am I doing wrong? Is there a working example anywhere I can use as a guide?

Lightmaps not working for android AR Foundation

I am using this asset so I can instantiate different baked prefabs in AR during runtime.
When I bake and instantiate the prefabs in the Unity editor everything works but when I build the project and test it on my android device the lightmaps seem to be broken and in the wrong places.

See example of a lab you can walk through in AR, the first image is instantiated in play mode in the editor and the second is instantiated on the device:
image
Screenshot_20210916-163719_CityGame

I am using URP and Unity 2020.2.6f1 (also tried in Unity 2021.1.21f1).

Ik bake my assets using the 'bake prefab lightmap' Set my meshes to static (static batching off). I read through the other issues and tried those aproaches aswell:

  • Including the light baked scene.
  • Copying the lightmaps into the same folder as the prefab.
  • Turn of static batching in settings.
  • Setting lightmap modes to custom and having everything on or off or cherry picked.
  • Setting instancing variants to keep all or strip unused.

have lightmaps for prefabs instead of scenes is really important for our project because it saves a lot of prossessing power and the scene used for AR is also used for other things (both the (AR) camera and objects are instantiated ar runtime depending on what the scene is used for at that time.

Lightmap not used after applying to prefab

I'm having some trouble using this. After baking my lights when I do the Assets > Bake Prefab Lightmaps everything seems to be going well. The script on the prefab is being populated.

But then when I look into the prefab, everything is unlit again. It's not being applied. And going back to the scene everything is gone as well. Do you have any insights on this issue?

I'm working on Unity 2019.2.9f1.

Does this work with AssetBundles?

I managed my prefabs in another Unity project and build them to assetbundle to use in the main project.
Does my workflow compatible with this script?

Double lighting

If I have a static room with a static torch and use "Bake Prefab Lightmaps" this results in double lighting. First, the walls of the room display the baked lighting, indirect in subtractive and baked indirect mode, and both direct and indirect in shadowmask mode. Second, the torch casts light in the scene yet again, because Unity does not recognize this was a baked light and should not be rerendered. During the baking process Unity will save which lights were baked and which were not, so as to avoid this issue. This project doesn't do that. As a result, the project is not useful for prefabs that themselves include lights.

Baking lightning on a prefab overwrite other prefabs lightmaps

Hi I don't really know if I'm trying to do something the script is not supposed to, or if I'm missing something.

I used this script to bake lightmaps on a level of my project which is loaded at runtime, and I didn't got any issues. But, once I bake another level, the lightmaps of all the previous are overwritten. I think it's because I use the same scene to bake all the levels, but if so, should I create a scene for every levels I need ?

Issue on iOS build vs Editor in URP 7.2.1

Come across an issue where we're trying to setup a lighting scene for an object at scale 100 in editor and the bake looks different in editor vs on iOS. This happens even when testing within the same scene. The lightmap scale looks incorrect on iOS.

Setup:

  • Unity 2019.3.3 and URP 7.2.1

  • Prefab with PrefabLighting script in scene at scale 100.

  • One Directional light

Any ideas?

Baked Objects Get Darker After Reloading Scene

Hi, thank you for this script it has really helped optimize performance in my mobile game.

However, I am having issues with game objects appearing darker after the scene is reloaded. Do you know if this issue is caused by the script or maybe something else?

In the video, the cars become darker after I reload the scene (Ignore the dark buildings):
ezgif com-video-to-gif

Before Reload:
LightmapIssue

After Reload:
LightmapIssue2

Any help would be greatly apperciated.

Not working on the build

Hey Ayfel,

Thanks for this amazing tool. In the editor this works great but on an actual build, the light data does not seem to apply correctly.

I've tested on Android and Windows without any luck. Also tried putting the light data inside Resources to make sure that the light data was bundled in the build.

Running on Unity 2018.2.20f1.

Any ideas?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.