找回密码
 立即注册
楼主: monery8

[脚本] Unity3D 读写txt 文件代码

[复制链接]
发表于 2013-2-1 00:23 | 显示全部楼层 |阅读模式

1.  在 unity3d 中新建一个  javascript  名为为 file.js
2.  写入如下代码:

import System.IO;

var fileName;



function OnGUI() {

  if (GUI.Button(Rect(10,10,100,50),"Write File")) {

  //fileName = Application.persistentDataPath + "/" + "test.txt";

  fileName = Application.dataPath + "/" + "test.txt";

    WriteFile(fileName);

  }

  if (GUI.Button(Rect(10,110,100,50),"Read File")) {

  //fileName = Application.persistentDataPath + "/" + "test.txt";

    fileName = Application.dataPath + "/" + "test.txt";

    ReadFile(fileName);

  }

}


//  写文件
function WriteFile(filepathIncludingFileName : String)

{

  fileWriter = File.CreateText(filepathIncludingFileName);
   fileWriter.WriteLine("Hello world");

  fileWriter.Close();

}


//读取文件
function ReadFile(filepathIncludingFileName : String) {

  sr = new File.OpenText(filepathIncludingFileName);



  input = "";

  while (true) {

    input = sr.ReadLine();

    if (input == null) { break; }

    Debug.Log("line="+input);

  }

  sr.Close();

}


3.  路径解释:
Application.persistentDataPath  所在位置为:
C:/Documents and Settings/atlas/Local Settings/Application Data/你的用户名/files/
且 PC, Mac, iOS and Android指向的位置相同  不需要针对每个平台去写

转自http://cl314413.blog.163.com/blo ... 762011112810251960/
Application.dataPath 所在位置为:
编辑器模式下  为 Assets文件夹
Windows build  模式下为  Data 文件夹
Mac build  模式下为 Contents文件夹
发表于 2013-2-13 22:18 | 显示全部楼层
看看 学习学习
发表于 2017-4-27 18:19 | 显示全部楼层
很不错
发表于 2017-4-27 18:46 | 显示全部楼层
好帖就是要顶
发表于 2017-4-27 18:27 | 显示全部楼层
顶顶多好
发表于 2017-4-27 18:22 | 显示全部楼层
真心顶
发表于 2017-4-27 18:40 | 显示全部楼层
难得一见的好帖
发表于 2017-4-28 13:08 | 显示全部楼层
很不错
发表于 2017-4-28 13:24 | 显示全部楼层
顶顶多好
发表于 2017-4-28 13:01 | 显示全部楼层
说的非常好
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-4 02:53 , Processed in 0.292971 second(s), 24 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表