Unity灯光烘焙动态加载代码参考及避坑

目前下面这个脚本只支持一张灯光烘焙贴图,不过调整下代码支持多张也不难,遇到的主要问题是如果外部打包好的场景第一次加载进来的时候烘焙贴图动态加载进来后没问题,但是在场景反复卸载和加载的时候烘焙贴图总是不起作用,后来发现就是在前一个场景卸载之后,添加一句代码:

LightmapSettings.lightmaps = null;(参考下面代码的第17行)

然后就没问题了。

using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;

public class LightMapLoader : MonoBehaviour
{
	static public LightMapLoader instance;

	void Awake()
	{
		instance = this;
	}

	void Start()
	{
		SceneLoader.instance.AddActAfterUnloadedCurScene(delegate { LightmapSettings.lightmaps = null; });
	}

	public void Set(string folderName)
	{
		folderName = folderName.Trim();
		if (folderName.Length <= 0) return;
		//
		string path = Application.streamingAssetsPath + "/" + folderName + "/LightMaps/" + (Application.platform == RuntimePlatform.WebGLPlayer ? "WebGL/" : "Window/");
		//
		LightmapData lightmapData = new LightmapData();
		//
		string loadLightPath = path + "lightmap-0_comp_light";
		StartCoroutine(GetAssetBundle(loadLightPath,
			(abLit) =>
			{
				if (abLit)
				{
					lightmapData.lightmapColor = abLit.LoadAsset<Texture2D>("Lightmap-0_comp_light.exr");
					abLit.Unload(false);

					string loadDirPath = path + "lightmap-0_comp_dir";
					StartCoroutine(GetAssetBundle(loadDirPath,
						(abDir) =>
						{
							if (abDir)
							{
								lightmapData.lightmapDir = abDir.LoadAsset<Texture2D>("Lightmap-0_comp_dir.png");
								abDir.Unload(false);
								LightmapSettings.lightmaps = new LightmapData[1] { lightmapData };
							}
						}));
				}
			}));
	}

	IEnumerator GetAssetBundle(string path, UnityAction<AssetBundle> onGetAssetBundle)
	{
		using (UnityWebRequest webRequest = UnityWebRequestAssetBundle.GetAssetBundle(path))
		{
			yield return webRequest.SendWebRequest();
			if (webRequest.result == UnityWebRequest.Result.Success)
			{
				AssetBundle ab = (webRequest.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
				onGetAssetBundle?.Invoke(ab);
			}
			else
			{
				Debug.Log("error = " + webRequest.error + "\n Load Path = " + path);
				onGetAssetBundle?.Invoke(null);
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/ttod/article/details/130151121