unity StreamingAssets路径

  我们在读写例如XML和TXT文件的时候,在电脑上和手机上路径不一致,造成了很多麻烦,其实有个简单的方法,在项目工程中新建一个StreamingAssets文件夹,把你的XML和TXT文件放到这里。

using UnityEngine; 
using System.Collections; 
using System.Xml; 
using System.Xml.Serialization; 
using System.IO; 
using System.Text; 
 
public class Reward  
 { 
   public int taskNo;
   
   public Task[] task = new Task[15];
   public Attribute attribute; 
   public Reward () {} 
   public struct Task
   { 
	  [XmlAttribute("taskReward")] 
	  public string taskReward{ get; set;} 
	  public Id id1; 
	  public Id id2;
      public Id id3;
   }
   public struct Id
   {
	  [XmlAttribute("flag")] 
	  public bool flag{ get; set;} 
	  [XmlAttribute("name")] 
	  public string name{ get; set;}
	  [XmlText()]
	  public string description{get;set;}
		
   }  
}

public class AchievementManager: MonoBehaviour { 
   Reward reward ; 
   FileInfo fileInfo;
   string _data; 
	
   void Start () 
   {   
      reward = new Reward();
	  LoadXML();
   } 
   void LoadXML() 
   { 
	  if(Application.platform == RuntimePlatform.IPhonePlayer)
	  {
		 fileInfo = new FileInfo(Application.dataPath + "/Raw/" + "Achievement.xml"); 
		  StreamReader r = fileInfo.OpenText(); 
         _data = r.ReadToEnd(); 
         r.Close(); 
	  }
	  else if(Application.platform == RuntimePlatform.Android)
	  {
		 fileInfo = new FileInfo(Application.streamingAssetsPath+"/Achievement.xml");
	     StartCoroutine("LoadWWW");
	  }
	  else
	  {
		 fileInfo = new FileInfo(Application.dataPath + "/StreamingAssets/"+ "Achievement.xml"); 
		 StreamReader r = fileInfo.OpenText(); 
         _data = r.ReadToEnd(); 
         r.Close(); 
      }	  
	  if(_data.ToString() != "") 
      { 
         reward = (Reward)DeserializeObject(_data);              
      } 
   }
   void OnGUI()
   {
	   GUI.Label(new Rect(0,0,Screen.width,Screen.height),"data:"+_data);	 
	   if(Input.GetKey(KeyCode.Space))
		{
			Application.Quit(); 
		}
   }
	
	IEnumerator LoadWWW()
	{
		WWW www = new WWW(Application.streamingAssetsPath+"/Achievement.xml");
		yield return www;
		_data =www.text;
	}
   public void Save()
   {     
      _data = SerializeObject(reward);
	  StreamWriter writer; 
      fileInfo.Delete();    
	  writer = fileInfo.CreateText(); 
      writer.Write(_data);
      writer.Close(); 
   }
   string UTF8ByteArrayToString(byte[] characters) 
   {      
      UTF8Encoding encoding = new UTF8Encoding(); 
      string constructedString = encoding.GetString(characters); 
      return (constructedString); 
   } 
 
   byte[] StringToUTF8ByteArray(string pXmlString) 
   { 
      UTF8Encoding encoding = new UTF8Encoding(); 
      byte[] byteArray = encoding.GetBytes(pXmlString); 
      return byteArray; 
   } 
 
   // Here we serialize our Reward object of reward 
   string SerializeObject(object pObject) 
   {
	  string XmlizedString = null; 
      MemoryStream memoryStream = new MemoryStream(); 
      XmlSerializer xs = new XmlSerializer(typeof(Reward)); 
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
      xs.Serialize(xmlTextWriter, pObject); 
      memoryStream = (MemoryStream)xmlTextWriter.BaseStream; 
      XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); 
      return XmlizedString; 
   } 
 
   // Here we deserialize it back into its original form 
   object DeserializeObject(string pXmlizedString) 
   { 
      XmlSerializer xs = new XmlSerializer(typeof(Reward)); 
      MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); 
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
      return xs.Deserialize(memoryStream); 
   } 
}


注:其实每个平台的路径都可以是Application.streamingAssetsPath+"/Achievement.xml"。但是android平台必须要用WWW加载,其他的平台貌似也可以的,自己试试哈,呵呵~~~

 

 

 

### UnityStreamingAssets 的读写方法 在 Unity 开发中,`StreamingAssets` 文件夹是一个特殊的位置,用于存储需要随项目一起发布的资源文件。这些文件通常不会被 Unity 自动压缩或处理,因此适合用来保存一些原始数据文件(如 `.txt`, `.xml`, 或者其他自定义格式)。以下是关于 `StreamingAssets` 文件夹的读取和写入操作的具体说明。 #### 1. **读取 StreamingAssets 文件** 对于 `StreamingAssets` 文件夹中的文件,可以通过路径访问其内容。需要注意的是,在 Android 平台上,该文件夹会被打包成 APK 内部的一部分,因此无法直接通过本地路径访问,而需要用 `WWW` 类或者 `UnityWebRequest` 来加载。 以下是一段代码示例展示如何读取 `StreamingAssets` 文件夹下的文本文件: ```csharp using System.IO; using UnityEngine; public class ReadStreamingAssetsExample : MonoBehaviour { void Start() { string filePath = Path.Combine(Application.streamingAssetsPath, "example.txt"); if (filePath.Contains(".android")) { // 如果是在Android平台上,则使用 WWW 加载 StartCoroutine(LoadTextFromAndroid(filePath)); } else { // 非Android平台可以直接读取 string data = File.ReadAllText(filePath); Debug.Log("Read from file: " + data); } } private IEnumerator LoadTextFromAndroid(string path) { using (var www = new WWW(path)) { yield return www; string result = www.text; Debug.Log("Read from Android asset: " + result); } } } ``` 上述代码展示了两种情况: - 在非 Android 平台下,可直接使用 `File.ReadAllText()` 方法[^1]。 - 在 Android 平台下,由于文件被打包到 APK 中,需借助 `WWW` 或 `UnityWebRequest` 进行异步加载[^2]。 --- #### 2. **写入 StreamingAssets 文件** 需要注意的是,`StreamingAssets` 是只读目录,开发者不能向其中写入新文件。如果需要实现类似功能,可以选择将文件复制到另一个可写的目录(如 `Application.persistentDataPath`),然后再对其进行修改或更新。 下面是一个简单的例子,演示如何从 `StreamingAssets` 复制文件到持久化数据路径并进行写入操作: ```csharp using System.IO; using UnityEngine; public class WriteToFileExample : MonoBehaviour { void Start() { string sourceFilePath = Path.Combine(Application.streamingAssetsPath, "example.txt"); string destinationFilePath = Path.Combine(Application.persistentDataPath, "copied_example.txt"); // 将文件StreamingAssets复制到persistentDataPath if (!File.Exists(destinationFilePath)) { if (sourceFilePath.Contains(".android")) { StartCoroutine(CopyFileFromAndroid(sourceFilePath, destinationFilePath)); } else { File.Copy(sourceFilePath, destinationFilePath); } } // 向目标文件追加内容 using (StreamWriter writer = File.AppendText(destinationFilePath)) { writer.WriteLine("\nThis is a new line added to the file."); } Debug.Log("Write operation completed!"); } private IEnumerator CopyFileFromAndroid(string sourcePath, string destPath) { using (var www = new WWW(sourcePath)) { yield return www; System.IO.File.WriteAllBytes(destPath, www.bytes); } } } ``` 此代码实现了以下逻辑: - 检查目标文件是否存在;如果不存在,则将其从 `StreamingAssets` 路径复制到 `persistentDataPath` 下。 - 使用 `StreamWriter` 对已存在的文件执行追加写入操作。 --- #### 总结 - 只能在特定条件下(如非 Android 平台)直接读取 `StreamingAssets` 文件的内容。 - 若涉及跨平台兼容性问题(尤其是 Android),应考虑使用 `WWW` 或 `UnityWebRequest` 实现文件加载。 - 不允许直接对 `StreamingAssets` 文件夹内的文件进行写入操作,建议先将文件复制至可写位置后再做进一步编辑。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值