从Unity2018开始,Unity支持使用Java源码文件作为插件在Unity工程中使用。在构建Android时会编译这些源码(该功能依赖于Gradle构建系统)
1. 创建Java文件
Assets->Plugins->Android->libs->UnityTools.java
package com.UnityPackage; import java.io.File; import android.os.Environment; import android.os.StatFs; public class UnityTools { public static long GetFreeStorageSpace() { try { File file = Environment.getDataDirectory(); StatFs stat = new StatFs(file.getPath()); return stat .getAvailableBytes(); //VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2 } catch (Exception e) { } return -1; } }
2. 创建C#文件
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; public class UnityAndroidTools { public static long GetFreeStorageSpace() { try { AndroidJavaObject javaObj = new AndroidJavaObject("com.UnityPakcage.UnityTools"); return javaObj.CallStatic<long>("GetFreeStorageSpace"); } catch(Exception e) { Debug.LogError(e); } return -1; } }