unity StreamingAssets路径

本文介绍在Unity项目中通过新建StreamingAssets文件夹来统一管理XML和TXT文件,解决路径不一致的问题,并提供了相关代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unity StreamingAssets路径

分类: Unity3D初步篇   3897人阅读  评论(1)  收藏  举报

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

[html]  view plain copy print ?
  1. using UnityEngine;   
  2. using System.Collections;   
  3. using System.Xml;   
  4. using System.Xml.Serialization;   
  5. using System.IO;   
  6. using System.Text;   
  7.    
  8. public class Reward    
  9.  {   
  10.    public int taskNo;  
  11.      
  12.    public Task[] task = new Task[15];  
  13.    public Attribute attribute;   
  14.    public Reward () {}   
  15.    public struct Task  
  16.    {   
  17.       [XmlAttribute("taskReward")]   
  18.       public string taskReward{ get; set;}   
  19.       public Id id1;   
  20.       public Id id2;  
  21.       public Id id3;  
  22.    }  
  23.    public struct Id  
  24.    {  
  25.       [XmlAttribute("flag")]   
  26.       public bool flag{ get; set;}   
  27.       [XmlAttribute("name")]   
  28.       public string name{ get; set;}  
  29.       [XmlText()]  
  30.       public string description{get;set;}  
  31.           
  32.    }    
  33. }  
  34.   
  35. public class AchievementManager: MonoBehaviour {   
  36.    Reward reward ;   
  37.    FileInfo fileInfo;  
  38.    string _data;   
  39.       
  40.    void Start ()   
  41.    {     
  42.       reward = new Reward();  
  43.       LoadXML();  
  44.    }   
  45.    void LoadXML()   
  46.    {   
  47.       if(Application.platform == RuntimePlatform.IPhonePlayer)  
  48.       {  
  49.          fileInfo = new FileInfo(Application.dataPath + "/Raw/" + "Achievement.xml");   
  50.           StreamReader r = fileInfo.OpenText();   
  51.          _data = r.ReadToEnd();   
  52.          r.Close();   
  53.       }  
  54.       else if(Application.platform == RuntimePlatform.Android)  
  55.       {  
  56.          fileInfo = new FileInfo(Application.streamingAssetsPath+"/Achievement.xml");  
  57.          StartCoroutine("LoadWWW");  
  58.       }  
  59.       else  
  60.       {  
  61.          fileInfo = new FileInfo(Application.dataPath + "/StreamingAssets/"+ "Achievement.xml");   
  62.          StreamReader r = fileInfo.OpenText();   
  63.          _data = r.ReadToEnd();   
  64.          r.Close();   
  65.       }     
  66.       if(_data.ToString() != "")   
  67.       {   
  68.          reward = (Reward)DeserializeObject(_data);                
  69.       }   
  70.    }  
  71.    void OnGUI()  
  72.    {  
  73.        GUI.Label(new Rect(0,0,Screen.width,Screen.height),"data:"+_data);      
  74.        if(Input.GetKey(KeyCode.Space))  
  75.         {  
  76.             Application.Quit();   
  77.         }  
  78.    }  
  79.       
  80.     IEnumerator LoadWWW()  
  81.     {  
  82.         WWW www = new WWW(Application.streamingAssetsPath+"/Achievement.xml");  
  83.         yield return www;  
  84.         _data =www.text;  
  85.     }  
  86.    public void Save()  
  87.    {       
  88.       _data = SerializeObject(reward);  
  89.       StreamWriter writer;   
  90.       fileInfo.Delete();      
  91.       writer = fileInfo.CreateText();   
  92.       writer.Write(_data);  
  93.       writer.Close();   
  94.    }  
  95.    string UTF8ByteArrayToString(byte[] characters)   
  96.    {        
  97.       UTF8Encoding encoding = new UTF8Encoding();   
  98.       string constructedString = encoding.GetString(characters);   
  99.       return (constructedString);   
  100.    }   
  101.    
  102.    byte[] StringToUTF8ByteArray(string pXmlString)   
  103.    {   
  104.       UTF8Encoding encoding = new UTF8Encoding();   
  105.       byte[] byteArray = encoding.GetBytes(pXmlString);   
  106.       return byteArray;   
  107.    }   
  108.    
  109.    // Here we serialize our Reward object of reward   
  110.    string SerializeObject(object pObject)   
  111.    {  
  112.       string XmlizedString = null;   
  113.       MemoryStream memoryStream = new MemoryStream();   
  114.       XmlSerializer xs = new XmlSerializer(typeof(Reward));   
  115.       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
  116.       xs.Serialize(xmlTextWriter, pObject);   
  117.       memoryStream = (MemoryStream)xmlTextWriter.BaseStream;   
  118.       XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());   
  119.       return XmlizedString;   
  120.    }   
  121.    
  122.    // Here we deserialize it back into its original form   
  123.    object DeserializeObject(string pXmlizedString)   
  124.    {   
  125.       XmlSerializer xs = new XmlSerializer(typeof(Reward));   
  126.       MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));   
  127.       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
  128.       return xs.Deserialize(memoryStream);   
  129.    }   
  130. }  


注:其实每个平台的路径都可以是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` 文件夹内的文件进行写入操作,建议先将文件复制至可写位置后再做进一步编辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值