加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Unity中将一串字符串保存到Unity中,保存成任意格式

发布时间:2020-12-16 08:56:28 所属栏目:百科 来源:网络整理
导读:using UnityEngine;using System.Collections;using System.Xml;using System;using System.Text;using System.IO;public class Weather : MonoBehaviour{XmlDocument xmlDoc;// Use this for initializationvoid Start (){xmlDoc = new XmlDocument ();Star
using UnityEngine;
using System.Collections;
using System.Xml;
using System;
using System.Text;
using System.IO;

public class Weather : MonoBehaviour
{
	XmlDocument xmlDoc;
	// Use this for initialization
	void Start ()
	{
		xmlDoc = new XmlDocument ();
		StartCoroutine (DownXml ());
	}
	
	// Update is called once per frame
	void Update ()
	{
	
	}

	IEnumerator DownXml ()
	{
		WWW www = new WWW ("http://flash.weather.com.cn/wmaps/xml/dalian.xml");
		yield return www;
		CreateFile (Application.dataPath,"myXml.xml",www.text);


	}



	void CreateFile (string path,string name,string info)
	{
		// 文件流信息
		StreamWriter sw;
		FileInfo t = new FileInfo (path + "//" + name);
		if (!t.Exists) {
			// 如果此文件不存在则创建
			sw = t.CreateText ();
			// 以行的形式写入信息
			sw.WriteLine (info);
		} else {
			// 如果此文件存在则打开
			sw = t.AppendText ();
		}


		// 关闭流
		sw.Close ();
		// 销毁流
		sw.Dispose ();

	}

	void DeleteFile (string path,string name)
	{
		File.Delete (path + "//" + name);
 	 
	}



}
代码中头文件需要注意一下,涉及到IO读取文件。创建文件、删除文件、读取文件的方法我也已经封装好,Start方法中为了避免上次保存文件的残留首先删除原来的文件,然后创建文件FileName.txt ,我们也可修改文件的类型的后缀名。这里我写的是.txt ,为了完整的让中文出现在IOS与Android中所以这里给文件中写的数据是”宣雨松MOMO”,最后在OnGUI中将读取文件的文本信息显示在屏幕中,脚本保存格式为UTF-16。

代码中我们保存文件的路径是Application.persistentDataPath。 如果你写的路径是 Application.dataPath在编辑器中是可以正常读取,但是在IOS与Android中是无法读取的,昨天问我的那个朋友就是因为这里路径写的有问题没能成功的写入文件。 Application.persistentDataPath路径就是将文件保存在手机的沙盒中,如果在编辑器中运行本程序文件将保存在Finder-》 资源库-》Caches-》你的工程-》保存的文件 。本例的路径就是 Finder->资源库-> Caches -> txt->FileName.txt。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读