Read/Write able paths on Unity iOS and Android
Most of the users are always worried about the path on which they can write data at runtime.
Sometimes we need to save screen shorts, or text files in our game or app.
So there I am going to give you an example to download and save image in your iOS and Android game with Unity3D.
void Start ()
{
StartCoroutine("getData");
}
This is the Start function of your class.
IEnumerator getData()
{
WWW www = new WWW("URL your your API");
float elapsedTime = 0.0f;
while (!www.isDone)
{
elapsedTime += Time.deltaTime;
if (elapsedTime >= 1000.0f) break;
yield return null;
}
if (!www.isDone || !string.IsNullOrEmpty(www.error)) {
Debug.LogError(string.Format("Fail Whale!\n{0}", www.error));
yield break;
}
response = www.text;
IDictionary val = MiniJSON.Json.Deserialize(response) as IDictionary;
string imageURL = val["url"].ToString();
imageName = val["imagename"].ToString();
imageURL = "http://"+imageURL;
Debug.Log(imageURL);
StartCoroutine(LoadImage(imageURL));
}
This will return you a json file...
IEnumerator LoadImage(string url)
{
#if UNITY_IPHONE
string path = GetiPhoneDocumentsPath();
#elif UNITY_ANDROID
string path = GetAndroidDocumentsPath();
#endif
path+="/"+imageName;
if(!File.Exists(path))
{
Debug.Log("File Not Exist... So Downloading....");
WWW www = new WWW(url);
yield return www;
Byte[] bytes = www.texture.EncodeToPNG();
Debug.Log("Writing File.....");
File.WriteAllBytes(path , bytes);
}
else{
Debug.Log("File Exist......");
}
StartCoroutine(loadImage(path));
}
You need to get paths. ? Here are the paths..
For iOS:-
string GetiPhoneDocumentsPath()
{
string path = Application.dataPath.Substring (0, Application.dataPath.Length - 5);
path = path.Substring(0, path.LastIndexOf('/'));
return path + "/Documents";
}
For Android:-
string GetAndroidDocumentsPath()
{
string path = Application.persistentDataPath;
return path;
}
And now Getting saved file...
IEnumerator loadImage(string path)
{
Debug.Log("Load Image......");
yield return new WaitForSeconds(1.0f);
Byte[] tBytes = File.ReadAllBytes(path);
Texture2D tTex = new Texture2D(512, 512,TextureFormat.ARGB32,false);
tTex.LoadImage(tBytes);
renderer.material.mainTexture = tTex;
}
i am sure you will like this...
have a happy coding.. :)
0 Comment(s)