- Home /
How to write pixels to a lightmap
I'm trying to do some post-processing of Beast-generated lightmaps, but I'm running into the problem that after writing out pixels (using SetPixels()) to the lightmap and Apply()'ing the changes, the lightmap remains unchanged. I've tried it both as a pure editor script, and also as an asset importer (where the post-processing is performed in a custom postprocessor).
Out of desperation just to see if my pixels were getting written in any form, I tried writing the lightmap back out as a PNG (using EncodeToPNG()), but I still don't get any modified result.
Any ideas?
Answer by Kryptos · Aug 17, 2011 at 07:41 AM
Did you ensure that your texture has property 'Read/Write Enabled' checked? (To see this property, you have to choose 'Advanced' as texture type in the TextureImporter component of your texture asset)
IMHO SetPixels() is just ignored if this property is not enabled.
Answer by Kryptos · Aug 18, 2011 at 07:26 AM
I tried yesterday to write to the lightmap and I didn't get any issue. Can you give a link to a simple project with this issue or post your code?
Here is the code sample I used:
void LateUpdate()
{
// Let's assume we get these coordinates by raycasting
// Coordinates retrieved that way are normalized, i.e. between 0 and 1
Vector2 lightmapCoord = GetCoordRaycast();
// I have a single lightmap in my scene, therefore it is the first occurence in the lightmap array.
Texture2D lightmap = LightmapSettings.lightmaps[0].lightmapFar;
// Get the current pixel (filtered)
Color lightmapColor =
lightmap.GetPixelBilinear( lightmapCoord.x, lightmapCoord.y );
Debug.Log(lightmapColor);
// Set a blood pixel ;)
lightmap.SetPixel( lightmapCoord.x*lightmap.width, lightmapCoord.y*lightmap.height, Color.red );
lightmap.Apply();
}
As a result, some kind of blooded tracks were following my character.
I guess I should clarify, I'm trying to actually write to the lightmap on disk in edit mode as opposed to at runtime. Nothing I do seems to "stick", in other words, the lightmaps remain unaffected.
Strangely, however, I tried your code snippet at runtime (using UV coords that begin at the lower-left and step toward the upper-right over time), and I couldn't get it to work either. The lightmap texture is marked as writable and its format is RGBA32. There has to be another element I'm missing... Do you happen to have a simple package you could post that demonstrates this? Perhaps I could look at that and figure out what the difference is between a working example and my test case. It could be that whatever is preventing it from working in edit mode is also preventing it at runtime, since your example should definitely work.
Never $$anonymous$$d, I just realized the reason it wasn't working for me was a float-to-int conversion problem (since SetPixel() requires ints). Your example is working for me now. Still not sure on the edit-time issue... thanks for your help!