异步批量烘焙光照贴图自动化打包
private void AsyncBake()
{
if (!Lightmapping.isRunning)
{
Lightmapping.completed = null;
Lightmapping.completed = TimeUsed;
Lightmapping.completed += ResetObjStatic;
Lightmapping.completed += SaveBakedLightMap;
Lightmapping.completed += BakeNewObj;
StartBake();
BakeNewObj();
}
else
{
Lightmapping.Cancel();
UpdateBakeProgress();
}
}
private void StartBake()
{
_curBakedIndex = 0;
if (_bakeList.Count == 0)
{
_status = "Nothing To Bake";
_bakeButton = "Bake";
}
}
private void BakeNewObj()
{
if (_curBakedIndex < _bakeList.Count)
{
_bakeList[_curBakedIndex].isStatic = true;
_timeStamp = DateTime.Now;
Lightmapping.BakeAsync();
_curBakedIndex++;
UpdateBakeProgress();
}
else
{
SetBakeState("Done");
}
}
private void UpdateBakeProgress()
{
if (Lightmapping.isRunning)
{
_status = "Baking " + _curBakedIndex + " of " + _bakeList.Count;
_bakeButton = "Cancel";
}
else
{
SetBakeState("Cancel");
}
}
private void SetBakeState(string state)
{
Lightmapping.completed = null;
_curBakedIndex = 0;
if (state == "Done")
{
_status = "Bake is done";
_bakeButton = "Bake";
}
else if (state == "Cancel")
{
_status = "Canceled";
_bakeButton = "Bake";
}
}
private void TimeUsed()
{
var bakeSpan = DateTime.Now - _timeStamp;
var bakeTime = string.Format("{0:D2}'{1:D2}'{2:D2}'", bakeSpan.Hours, bakeSpan.Minutes, bakeSpan.Seconds);
Debug.Log(_curBakedIndex + "/" + _bakeList.Count + " " + _bakeList[_curBakedIndex - 1].name + ":bakeTime: " + bakeTime + " At " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
private void ResetObjStatic()
{
_bakeList[_curBakedIndex - 1].isStatic = false;
}
private void SaveBakedLightMap()
{
var obj = _bakeList[_curBakedIndex - 1];
var info = obj.GetComponent<BakeInfo>();
if (!info)
{
info = obj.AddComponent<BakeInfo>();
}
var render = obj.GetComponent<Renderer>();
//clear
if (info.lightmapTexture)
{
DeleteLightMapFile(info.Name);
}
ClearAssetBundleName();
//assign
//info.lightmapIndex = render.lightmapIndex;
info.lightmapScaleOffset = render.lightmapScaleOffset;
info.Name = "lm" + DateTime.Now.ToString("MMddHHmmss");
//creatAsset
var mapAsset = CreateInstance<LightmapTexture>();
mapAsset.LightmapColor = LightmapSettings.lightmaps[0].lightmapColor;
var assetPath = _lightInfoPath + "/" + info.Name + ".prefab";
AssetDatabase.CreateAsset(mapAsset, assetPath);
//buildBundle
var assetImport = AssetImporter.GetAtPath(assetPath);
assetImport.SetAssetBundleNameAndVariant(info.Name, "bundle");
BuildPipeline.BuildAssetBundles(_lightBundlePath, BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget);
}
示例
来源:CSDN
作者:作茧自缚的蚕
链接:https://blog.csdn.net/m0_46124411/article/details/103984453