C# Unity游戏开发——Excel中的数据是如何到游戏中的 (三)

本帖是延续的:C# Unity游戏开发——Excel中的数据是如何到游戏中的 (二)

 

前几天有点事情所以没有继续更新,今天我们接着说。上个帖子中我们看到已经把Excel数据生成了.bin的文件,不过其实这样到游戏中还是不能用的。主要有两个方面,1.bin文件的后缀使我们随便取的名字,但是这种文件Unity不买账。因为Unity中的二进制文件必须是以.bytes命名的。2.在写文件之前其实还可以对二进制进行压缩,这样可以最大化节省设备空间。也就是说我们在生成数据实例后还需要做以下几件事:序列化 -> 压缩 -> 写文件.

 

 

方式和上帖中的方式基本相同,但是因为我们要对序列化的数据进行压缩,所以不能直接把数据序列化进文件流,二是序列化进一个MemoryStream然后取出二进制数据压缩后再进行写文件。

        MemoryStream ms = new MemoryStream();
        Serializer.Serialize<StaticData>(ms, (StaticData)staticData);
        byte[] byts = ms.ToArray();
        System.IO.FileStream stream1 = new System.IO.FileStream(Application.dataPath + "/Resources/StaticDatas.bytes", System.IO.FileMode.Create);
        System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream1);
        writer.Write(GZIP.Encode(byts));
        writer.Close();
        stream1.Close();

哦啦,加上这几句就Ok了。说明一下我们使用了ICSharpCode.SharpZipLib.GZip这个dll,GZIP的使用方法可以参考这个地址 http://community.sharpdevelop.net/forums/t/11005.aspx,这里我写了个GZIP工具类就两个方法

    public static byte[] Encode(byte[] bin)
    {
        MemoryStream ms = new MemoryStream();
        GZipOutputStream gzp = new GZipOutputStream(ms);
        gzp.Write(bin, 0, bin.Length);
        gzp.Close();
        return ms.ToArray();
    }

    public static byte[] Decode(byte[] bin)
    {
        GZipInputStream gzp = new GZipInputStream(new MemoryStream(bin));
        MemoryStream re = new MemoryStream();
        int count = 0;
        byte[] data = new byte[4096];
        while ((count = gzp.Read(data, 0, data.Length)) != 0)
        {
            re.Write(data, 0, count);
        }
        return re.ToArray();
    }
View Code

 

然后,我们在看看游戏中是怎么用的。使用也很简单,因为前面已经把类什么的都生成好了,所以,看代码把。

        byte[] bytes = (Resources.Load("StaticDatas") as TextAsset).bytes;
        MemoryStream ms = new MemoryStream(GZIP.Decode(bytes));
        StaticData data = Serializer.Deserialize<StaticData>(ms);

现在我们游戏中就能看到数据了,使用的时候直接data.就可以啦。

哦了,至此本课题结束。

每个人都会经历从不会到会的过程,如果有什么纰漏还请大家多指教!谢谢啦!

posted @ 2015-06-06 22:10  追峰人  阅读(1775)  评论(0编辑  收藏  举报