天天看點

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 腳本, 無法設定....");

                }

            }

        }

    }

}

繼續閱讀