Я построил приложение для Android в Unity, которое содержит сцены, в моем приложении есть 3 сцены, одна из них в Apk Build, а другие 2 - адресаты (упакованные как .bundle), и я хранил их на SD -карте. В сцене, которая находится в сборке APK, есть 2 кнопки для загрузки этих упакованных сцен (хранящихся на SD -карте) с SD -карты во время выполнения, но когда я строю APK и установлен на устройстве и открываю ее, я нажимаю на одну из кнопков, затем сцены, хранящиеся/загруженные на SD -карту, не загружены. . < /p>
Я хочу получить доступ к SD -карте и файлам из нее во время выполнения в приложении и загрузить файлы внутри него в приложении. Я хочу прочитать сохраненные данные с SD Card. < /p>
Android версия: Android 7
api Уровень: 25 < /p>
code. разрешение < /p>
< /code>
this code s for load scenes and access path
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.Android;
public class NewSDCARD : MonoBehaviour
{
IEnumerator Start()
{
#if UNITY_ANDROID && !UNITY_EDITOR
bool asked = false;
// Check if permission is already granted
while (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead))
{
if (!asked)
{
Permission.RequestUserPermission(Permission.ExternalStorageRead);
asked = true;
}
Debug.Log("Waiting for external storage permission...");
yield return new WaitForSeconds(0.5f);
}
// Optionally also check for WRITE_EXTERNAL_STORAGE (for older Androids)
if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
{
Permission.RequestUserPermission(Permission.ExternalStorageWrite);
yield return new WaitForSeconds(0.5f);
}
#endif
// Get SD card path from Java plugin
string realPath = AndroidStorageHelper.GetRealSdCardPath();
if (string.IsNullOrEmpty(realPath))
{
Debug.LogError("Could not get SD card path");
yield break;
}
string basePath = $"file://{realPath}/UnityRemoteAssets/Addressables";
Debug.Log("Using base path: " + basePath);
// Redirect internal Addressable paths
Addressables.InternalIdTransformFunc = (location) =>
{
string fileName = System.IO.Path.GetFileName(location.InternalId);
return $"{basePath}/{fileName}";
};
// Load the remote catalog
string catalogPath = $"{basePath}/catalog_v2.json";
var catalogHandle = Addressables.LoadContentCatalogAsync(catalogPath);
yield return catalogHandle;
if (catalogHandle.Status != AsyncOperationStatus.Succeeded)
{
Debug.LogError($" Failed to load Addressables catalog at: {catalogPath}");
yield break;
}
Debug.Log(" Addressables catalog loaded successfully from SD card.");
#if UNITY_EDITOR
Debug.Log("Running in Editor, skipping SD card load logic.");
yield break;
#endif
}
public void LoadScene(string sceneName)
{
Debug.Log("Loading scene: " + sceneName);
Addressables.LoadSceneAsync(sceneName, LoadSceneMode.Single);
}
}
using UnityEngine;
public static class AndroidStorageHelper
{
#if UNITY_ANDROID && !UNITY_EDITOR
private static AndroidJavaObject activityContext = null;
public static string GetRealSdCardPath()
{
if (activityContext == null)
{
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
activityContext = unityPlayer.GetStatic("currentActivity");
}
}
using (AndroidJavaObject plugin = new AndroidJavaObject("com.voidstudio.storageplugin.SDCardPlugin", activityContext))
{
return plugin.Call("getSdCardPath");
}
}
#else
public static string GetRealSdCardPath()
{
return "MockSdCardPath_For_Editor_Testing"; // Use mock in Editor
}
#endif
}
So, please if someone know about it can provide me the solution
Подробнее здесь: https://stackoverflow.com/questions/797 ... at-runtime
Невозможно получить доступ к SD -карте в Android Application (Unity) во время выполнения. ⇐ Android
Форум для тех, кто программирует под Android
1753768485
Anonymous
Я построил приложение для Android в Unity, которое содержит сцены, в моем приложении есть 3 сцены, одна из них в Apk Build, а другие 2 - адресаты (упакованные как .bundle), и я хранил их на SD -карте. В сцене, которая находится в сборке APK, есть 2 кнопки для загрузки этих упакованных сцен (хранящихся на SD -карте) с SD -карты во время выполнения, но когда я строю APK и установлен на устройстве и открываю ее, я нажимаю на одну из кнопков, затем сцены, хранящиеся/загруженные на SD -карту, не загружены. . < /p>
Я хочу получить доступ к SD -карте и файлам из нее во время выполнения в приложении и загрузить файлы внутри него в приложении. Я хочу прочитать сохраненные данные с SD Card. < /p>
Android версия: Android 7
api Уровень: 25 < /p>
code. разрешение < /p>
< /code>
this code s for load scenes and access path
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.Android;
public class NewSDCARD : MonoBehaviour
{
IEnumerator Start()
{
#if UNITY_ANDROID && !UNITY_EDITOR
bool asked = false;
// Check if permission is already granted
while (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead))
{
if (!asked)
{
Permission.RequestUserPermission(Permission.ExternalStorageRead);
asked = true;
}
Debug.Log("Waiting for external storage permission...");
yield return new WaitForSeconds(0.5f);
}
// Optionally also check for WRITE_EXTERNAL_STORAGE (for older Androids)
if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
{
Permission.RequestUserPermission(Permission.ExternalStorageWrite);
yield return new WaitForSeconds(0.5f);
}
#endif
// Get SD card path from Java plugin
string realPath = AndroidStorageHelper.GetRealSdCardPath();
if (string.IsNullOrEmpty(realPath))
{
Debug.LogError("Could not get SD card path");
yield break;
}
string basePath = $"file://{realPath}/UnityRemoteAssets/Addressables";
Debug.Log("Using base path: " + basePath);
// Redirect internal Addressable paths
Addressables.InternalIdTransformFunc = (location) =>
{
string fileName = System.IO.Path.GetFileName(location.InternalId);
return $"{basePath}/{fileName}";
};
// Load the remote catalog
string catalogPath = $"{basePath}/catalog_v2.json";
var catalogHandle = Addressables.LoadContentCatalogAsync(catalogPath);
yield return catalogHandle;
if (catalogHandle.Status != AsyncOperationStatus.Succeeded)
{
Debug.LogError($" Failed to load Addressables catalog at: {catalogPath}");
yield break;
}
Debug.Log(" Addressables catalog loaded successfully from SD card.");
#if UNITY_EDITOR
Debug.Log("Running in Editor, skipping SD card load logic.");
yield break;
#endif
}
public void LoadScene(string sceneName)
{
Debug.Log("Loading scene: " + sceneName);
Addressables.LoadSceneAsync(sceneName, LoadSceneMode.Single);
}
}
using UnityEngine;
public static class AndroidStorageHelper
{
#if UNITY_ANDROID && !UNITY_EDITOR
private static AndroidJavaObject activityContext = null;
public static string GetRealSdCardPath()
{
if (activityContext == null)
{
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
activityContext = unityPlayer.GetStatic("currentActivity");
}
}
using (AndroidJavaObject plugin = new AndroidJavaObject("com.voidstudio.storageplugin.SDCardPlugin", activityContext))
{
return plugin.Call("getSdCardPath");
}
}
#else
public static string GetRealSdCardPath()
{
return "MockSdCardPath_For_Editor_Testing"; // Use mock in Editor
}
#endif
}
So, please if someone know about it can provide me the solution
Подробнее здесь: [url]https://stackoverflow.com/questions/79714392/unable-to-access-sd-card-in-android-applicationunity-at-runtime[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия