天天看点

Unity 解决 动态设置Lightmap 贴图会歪的问题

在unity烘培好lightmap后lightmap信息会被保存在unity中, 而不在fbx中,这就意味着你把模型拿出去修改下再回来lightmap就没了, 更常见的情况是美工把fbx和lightmap给你,你完全无法使用. 因为unity没有提供给模型设置lightmap信息的方法.

百度了下发现这个文章:http://blog.sina.com.cn/s/blog_5b6cb9500101cplo.html (感谢作者)里面提供了设置lightmap信息的方法,但是有bug,里面TestLightmapingInfo()方法中直接把lightmapTilingOffset(Vector4) tostring了,这样界面上输出的值就会自动保留一位小数,就导致了严重的误差.....这坑了我好久 -  -, 下面我写了个正常的版本,还包括直接在编辑模型下设置lightmap信息 :

/// <summary>

/// 输出和设置Lightmap信息

/// </summary>

public class PrintLightmapMessage : EditorWindow

{

    [MenuItem("Batch/" + "测试Lightmapping信息 ")]

    static void TestLightmapingInfo()

    {

        GameObject[] tempObject;

        if (Selection.activeGameObject)

        {

            tempObject = Selection.gameObjects;

            for (int i = 0; i < tempObject.Length; i++)

            {

                Debug.Log("Object name: "  + tempObject[i].name);

                Debug.Log("Lightmaping Index: " + tempObject[i].renderer.lightmapIndex);

                Debug.Log("Lightmaping Offset.x: " + tempObject[i].renderer.lightmapTilingOffset.x);

                Debug.Log("Lightmaping Offset.y: " + tempObject[i].renderer.lightmapTilingOffset.y);

                Debug.Log("Lightmaping Offset.z: " + tempObject[i].renderer.lightmapTilingOffset.z);

                Debug.Log("Lightmaping Offset.w: " + tempObject[i].renderer.lightmapTilingOffset.w);

            }

        }

    }

    [MenuItem("Batch/" + "设置Lightmapping信息")]

    static void SetLightmapingInfo()

    {

        GameObject[] tempObject;

        if (Selection.activeGameObject)

        {

            tempObject = Selection.gameObjects;

            for (int i = 0; i < tempObject.Length; i++)

            {

                LightmapAssignment la = tempObject[i].GetComponent<LightmapAssignment>();

                if (la != null)

                {

                    Debug.Log("set Object name: " + tempObject[i].name);

                    Debug.Log("Lightmaping Index: " + la.lightmapIndex);

                    Debug.Log("Lightmaping Offset.x: " + tempObject[i].renderer.lightmapTilingOffset.x);

                    Debug.Log("Lightmaping Offset.y: " + tempObject[i].renderer.lightmapTilingOffset.y);

                    Debug.Log("Lightmaping Offset.z: " + tempObject[i].renderer.lightmapTilingOffset.z);

                    Debug.Log("Lightmaping Offset.w: " + tempObject[i].renderer.lightmapTilingOffset.w);

                    la.gameObject.renderer.lightmapIndex = la.lightmapIndex;

                    la.gameObject.renderer.lightmapTilingOffset = la.lightmapTilingOffset;

                }

                else

                {

                    Debug.Log("在物体 '" + tempObject[i].name + "' 上没有找到 LightmapAssignment 脚本, 无法设置....");

                }

            }

        }

    }

}

继续阅读