Unity 预设Lightmap信息丢失 使用ScriptableObject保存Lightmap信息动态赋值
以下代码都是手敲完成,不是源工程中复制的,如有错误请下载源工程查看
动态加载预设或者修改预设信息时 预设Lightmap信息丢失,需要将预设Lightmap信息保存起来,加载完成后动态赋值一次。
选择了使用ScriptableObject进行数据保存。
先创建ScriptableObject类(Lightmap和对象关联字段去掉了)。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Data/ScripttableTest")]
public class ScripttableTest : ScriptableObject
{
public List<LightmapInfo> lightmapInfos = new List<LightmapInfo>();
}
[System.Serializable]
public class LightmapInfo
{
public int lightmapIndex;
public Vector4 lightmapScaleOffset;
}
然后Creat一个ScriptableObject资源
接下来是信息记录部分,依然在编辑器下完成:
首先获取需要保存的对象,保存Lightmap信息:
GameObject[] gameObjects = Selection.gameObjects;
if (gameObjects != null && gameObjects.Length > 0)
{
int lenght = gameObjects.Length;
GameObject go;
Renderer renderer;
for (int i = 0; i < lenght; i++)
{
go = gameObjects[i];
renderer = go .GetComponent<Renderer>();
lightmapData.lightmapIndex = renderer.lightmapIndex;
lightmapData.lightmapScaleOffset = renderer.lightmapScaleOffset;
}
}
或者不打开场景,去场景固定对象下遍历,保存方法入上:
GameObject[] gameObjects = Selection.gameObjects;
UnityEngine.Object[] selectObjects = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets);
if (selectObjects != null && selectObjects.Length != 0)
{
string assetPath;
UnityEngine.Object asset = null;
GameObject saveNode = null;
bool needSave = false;
for (int i = 0; i < selectObjects.Length; ++i)
{
needSave = false;
assetPath = AssetDatabase.GetAssetPath(selectObjects[i]);
foreach (string extName in assetType)
{
if (assetPath.EndsWith(extName))
{
needSave = true;
break;
}
}
if (!needSave)
continue;
asset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(UnityEngine.Object)) as UnityEngine.Object;
EditorSceneManager.OpenScene(assetPath);
saveNode = GameObject.Find("RootPoint");
if (saveNode == null)
{
Debug.LogError("场景没有RootPoint节点!!");
continue;
}
EditorApplication.SaveScene();
Debug.Log(string.Format("场景{0}的光照贴图信息保存完成", asset.name));
}
AssetDatabase.SaveAssets();
}
接下来就是动态赋值,在预设加载完成后,获取所有Renderer进行赋值,赋值前后对比: