unity文件写入与读取
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEngine.SceneManagement; using System; using System.IO; using System.Runtime.InteropServices; public class GridEditor : EditorWindow { public static string _gridPath = "Assets/Scence/Data/Grid/"; public static float _perGridSize = 0.5f; public static float _gridX = 256; public static float _gridZ = 256; public static float _bottomHeight = -327; public static float _hafRayLength = 500; [MenuItem("Tools/GenerateGrid")] private static void GenerateGrid() { Scene scene = SceneManager.GetActiveScene(); if (!scene.IsValid()) { EditorUtility.DisplayDialog("1", "2", "OK"); return; } string heightPath = _gridPath + scene.name + ".bytes"; if (File.Exists(heightPath)) File.Delete(heightPath); FileStream fs_h = new FileStream(heightPath, FileMode.CreateNew); BinaryWriter bw_h = new BinaryWriter(fs_h); float haf = _perGridSize * 0.5f; float height = _bottomHeight * 100f; Vector3 rayDir = Vector3.down; Vector3 rayOrig = Vector3.zero; int maskLayerHeight = LayerMask.GetMask("Ground"); RaycastHit rayHit; bool isHit = false; for (float z = haf; z < _gridX + haf; z += _perGridSize) { for (float x = haf; x < _gridZ + haf; x += _perGridSize) { rayOrig.Set(x, _hafRayLength, z); height = _bottomHeight * 100f; isHit = Physics.Raycast(rayOrig, rayDir, out rayHit, _hafRayLength * 2, maskLayerHeight); if (isHit) { height = (float)Math.Round(rayHit.point.y, 2) * 100f; height = Mathf.Max(height, _bottomHeight * 100f); height = Mathf.Min(height, -_bottomHeight * 100f); } bw_h.Write((short)height); } } bw_h.Flush(); bw_h.Close(); fs_h.Close(); } private static short[] heightData; [MenuItem("Tools/ReadGrid")] private static void ReadGrid() { TextAsset heightAsset = (TextAsset)GetByteAsset("GridTest"); if (heightAsset) { heightData = new short[(int)(_gridX / _perGridSize) * (int)(_gridZ / _perGridSize)]; System.IntPtr heightPtr = Marshal.UnsafeAddrOfPinnedArrayElement(heightAsset.bytes, 0); Marshal.Copy(heightPtr, heightData, 0, heightData.Length); } else { Debug.Log("read height Asset error"); return; } for (int j = 0; j < heightData.Length; j++) { //Debug.Log(heightData[j] * 0.01f); } } private static UnityEngine.Object GetByteAsset(string resName, string ext = ".bytes") { string resPath = string.Format("{0}{1}" + ext, _gridPath, resName); UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath(resPath, typeof(UnityEngine.Object)); return obj; } }
作者:大表哥的笔记
提示:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果觉得还有帮助的话,可以点一下右下角的【推荐】,希望能够持续的为大家带来好的技术文章!想跟我一起进步么?那就【关注】我吧。
如果对文章有任何问题,都可以再评论中留言,我会尽可能的答复您,谢谢你的阅读