Unity3D开发之不同平台二进制资源文件的读取

Unity项目中需要读取一些二进制资源文件的时候,假设本项目资源是放在Assets/StreamingAssets/Data/文件夹下,这时候不同平台的读取方式是不一样的。直接贴码。


private static string RootPath
	{
		get{
			if(Application.platform == RuntimePlatform.IPhonePlayer)
			{
				return Application.dataPath +"/Raw/Data/";
			}
			else if(Application.platform == RuntimePlatform.Android)
			{
				return "jar:file://" + Application.dataPath + "!/assets/Data/"
			}
			else
			{
				return Application.dataPath + "/StreamingAssets/Data/";
			}
		}
	}


public static string ReadFile (string name)
	{
		string fileContent; 
		if(Application.platform == RuntimePlatform.Android)
		{
			WWW www = new WWW(RootPath + name);
			while(!www.isDone){};
			fileContent = www.text;
		}
		else
		{
			StreamReader sr = null;
			try{
				sr = File.OpenText(RootPath + name);
			}
			catch(Exception e){
				return null;
			}
			    
			while ((fileContent = sr.ReadLine()) != null) {
				break; 
			}
			sr.Close ();
			sr.Dispose ();
		}
		return fileContent;
	}

直接用资源名称作为参数,比如有个资源文件位置为:“Assets/StreamingAssets/Data/mydata.txt”,就可以ReadFile("mydata.txt")即可。

你可能感兴趣的:(unity3d,android,IOS)