Unity Android端 文件读写

Unity Android端路径下文件读写

持久化路径:

Application.persistentDataPath

其他路径:
在这里插入图片描述

	private void PathTest()
    {
    
    
        string path = "/storage/emulated/0/TestFolder/";
        if (!Directory.Exists(path))
        {
    
    
            Directory.CreateDirectory(path);
            Debug.Log("Found Path");
            using (FileStream fs = new FileStream(path + "TestText.txt", FileMode.Append, FileAccess.Write))
            {
    
    
                byte[] bytes = Encoding.UTF8.GetBytes("Hello,world啊");
                fs.Write(bytes, 0, bytes.Length);
            }
            Debug.Log("Write succeed");
            if (!Directory.Exists(path + "1.txt"))
            {
    
    
                Debug.Log(File.ReadAllText(path + "1.txt"));
                Debug.Log("Read succeed");
            }
        }
        else
        {
    
    
            Debug.Log("Path Not Found" + path);
        }
    }

安卓10以上需要清单文件增加内容,启用自定义Manifest
在这里插入图片描述

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

注意: 旧版本Unity需要自己获取权限

    public static void AutoRequestPermissions(string[] permissions
        , Action<string> onGranted = null
        , Action<string> onDenied = null
        , Action<string> onDeniedAndDontAskAgain = null)
    {
    
    
#if UNITY_ANDROID && !UNITY_EDITOR
            PermissionCallbacks callbacks = new PermissionCallbacks();
            callbacks.PermissionGranted += onGranted;
            callbacks.PermissionDenied += onDenied;
            callbacks.PermissionDeniedAndDontAskAgain += onDeniedAndDontAskAgain;

            var needRequest = permissions.Where(x=> !Permission.HasUserAuthorizedPermission(x)).ToArray();
            Permission.RequestUserPermissions(needRequest, callbacks);
#endif
    }

调用方法,在Start中获取

	private void Start(){
    
    
		RequestPermission();
	}

	public void RequestPermission()
	{
    
    
	    AndroidSDK.AutoRequestPermissions(new string[] {
    
     Permission.ExternalStorageWrite, Permission.ExternalStorageRead, Permission.Microphone });
	}

猜你喜欢

转载自blog.csdn.net/weixin_44347839/article/details/133137689