Application.dataPath使用中的注意事项

在Unity开发中Application.dataPath一直是很多人使用的API特别是移动端, 最近在做一款应用级的应用的时候需要用到截图功能保存本地, 代码都有但是就是和结果不对, 最终一步步试错才终于明白,Application.dataPath是不允许在移动端使用的, 如果移动端有使用的话会直接卡住! ? 哎 , 真实绕了个大弯啊 ! 这里做个采坑总结,希望伙伴们引以为鉴 .

using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;

public class SavedScreen : MonoBehaviour
{
	[SerializeField]
	public Text text = null;
	void Start()
	{
		text = GameObject.Find("Text").GetComponent<Text>();
		// 开启一个协程
		StartCoroutine(UploadPNG());
	}

	// 定义一个协程
	IEnumerator UploadPNG()
	{

		// 因为"WaitForEndOfFrame"在OnGUI之后执行
		// 所以我们只在渲染完成之后才读取屏幕上的画面
		yield return new WaitForEndOfFrame();

		int width = Screen.width;
		int height = Screen.height;
		// 创建一个屏幕大小的纹理,RGB24 位格(24位格没有透明通道,32位的有)
		Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);

		// 读取屏幕内容到我们自定义的纹理图片中
		tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
		// 保存前面对纹理的修改
		tex.Apply();

		// 编码纹理为PNG格式
		byte[] bytes = tex.EncodeToPNG();
		// 销毁无用的图片纹理
		Destroy(tex);

		// 将字节保存成图片,这个路径只能在PC端对图片进行读写操作
		//File.WriteAllBytes(Application.dataPath + "/onPcSavedScreen.png", bytes);
		text.text = "1234";
		// 这个路径会将图片保存到手机的沙盒中,这样就可以在手机上对其进行读写操作了
		File.WriteAllBytes(Application.persistentDataPath + "/onMobileSavedScreen1.png", bytes);

		text.text = File.Exists(Application.persistentDataPath + "/onMobileSavedScreen.png").ToString();

		WWW www = new WWW(Application.persistentDataPath + "/onMobileSavedScreen.png");
		yield return www;
	}
}
发布了31 篇原创文章 · 获赞 14 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/s15100007883/article/details/79134982