当前位置: 首页> 娱乐> 八卦 > 手机网页制作html_苏州网站建设代理渠道_discuz论坛seo设置_百度客服人工电话24

手机网页制作html_苏州网站建设代理渠道_discuz论坛seo设置_百度客服人工电话24

时间:2025/9/6 12:27:07来源:https://blog.csdn.net/2301_77947509/article/details/143650086 浏览次数:0次
手机网页制作html_苏州网站建设代理渠道_discuz论坛seo设置_百度客服人工电话24

如题,我写一个测试的文本文档吧

来看一下总结出来的思路

除了textasset常用resources加载textasset类型之外

 其他方式皆可读取unity内特定文件和项目外文件,有些还可以向文件写入内容

 

非文件流

1.TextAsset (可以依赖Resources路径,只读)

Unity - 脚本 API:TextAsset

这是Unity提供的读取原始文本和二进制的一个类,使用起来也非常的方便

如果你不知道什么是Resources,请参考这篇文章

Unity数据持久化 万物之源Resources动态资源加载_unity 动态加载资源-CSDN博客

 简单的演示代码

    // Start is called before the first frame updatevoid Start(){TextAsset str = Resources.Load<TextAsset>("Test");if(str!=null){Debug.Log(str.text);}else{Debug.LogError("未加载到文件");}}

 2.File(System.IO 读取项目外文件,可读可写)

        注意这种方法,读取文件路径要双斜杠,原因是 转义字符+再转义 = 原字符 这个规则

 string testPath = "C:\\Users\\Nharker\\Desktop\\Test.txt";if (File.Exists(testPath)){Debug.Log(testPath);string str = File.ReadAllText(testPath);Debug.Log(str);}

        

3. Application.persistentDataPath(可读可写)

        这个就不做演示了,就是把File的路径改为这个就行了,但是我要说一句这个路径根据不同平台有所出入,所以不是绝对的,具体请查看官方文档Application-persistentDataPath - Unity 脚本 API

文件流

1.字符流读取外部文件(System.IO 可读可写)

FileStream 通常用于二进制文件读取,当然也可以读字符串

  string testPath = "C:\\Users\\Nharker\\Desktop\\Test.txt";using (FileStream fs = new FileStream(testPath, FileMode.Open)) {byte[] chars =new byte[fs.Length];fs.Read(chars, 0, chars.Length);//参数: 读取到哪个数组 , 从第几位开始 ,读取多长的字节string str =System.Text.Encoding.UTF8.GetString(chars);Debug.Log(str);} 

StreamReader

   using (StreamReader reader = new StreamReader(testPath)) {string line;while ((line = reader.ReadLine()) != null) {Debug.Log(line);}}


        StreamWriter

   using (StreamWriter writer = new StreamWriter(writePath)){writer.Write(content);}

这个就是C#提供的写入文件的api,我认为不如FileStream 只需要修改filemode 然后调用fs.wrte的api即可

二者区别

2. 文件流读取 但是依赖StreamingAssets(只读)

           众所周知,StreamingAssets是unity的一个只读的路径,可以在其中存放文件流

   

            有疑问请自行查看官方文档,Application-streamingAssetsPath - Unity 脚本 API

   using (FileStream fs = File.Open(Application.streamingAssetsPath + "/Test.txt", FileMode.Open)) {byte[] chars = new byte[fs.Length];fs.Read(chars, 0, chars.Length);string str = System.Text.Encoding.UTF8.GetString(chars);Debug.Log(str);}

 using (StreamReader reader = new StreamReader(Application.streamingAssetsPath + "/Test.txt")) {string result = reader.ReadToEnd();Debug.Log(result);}

     

        

关键字:手机网页制作html_苏州网站建设代理渠道_discuz论坛seo设置_百度客服人工电话24

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: