gwiazdorrr / betterstreamingassets Goto Github PK
View Code? Open in Web Editor NEWA plugin for Unity that lets you access Streaming Assets directly on Android.
License: MIT License
A plugin for Unity that lets you access Streaming Assets directly on Android.
License: MIT License
So I am writing some unit tests now. And I need to test a piece of code that uses BetterStreamingAssets.
Unfortunately, I realized that it just does not work. For example, BetterStreamingAssets.GetFiles returns an empty string in edit mode, etc.
From Asset Store review:
When getting the file names, those with special characters like "ç" or "~" came with a white square in the text.
Needs to be investigated.
Platform:
Code:
BetterStreamingAssets.Initialize();
System.UnauthorizedAccessException:
Access to the path \'/data/data/{appName}/pram-shadow-files\' is denied.\n
I found the code of GetStreamingAssetsInfoFromJar
with File.OpenRead
in ApkImp
.
I'm trying to use this for StreamingAssets and cannot get it to work. I'm getting an error "IOException: Invalid characters" when I try to read from an existing json file.
I tried replacing File.ReadAllText(filePath) with BetterStreamingAssets.ReadAllText(filePath). But got the error above. Can you provide documentation on how to read from the StreamingAssets folder?
Below is my code that's using File to read and write, but it doesn't work on Android. How do I use your plugin?
public void LoadLocalizedText()
{
LocalizationData.localizedText = new StringStringDictionary();
string filePath = Path.Combine(Application.streamingAssetsPath, fileName + ".json").Replace("\\", "/");
Debug.Log(filePath);
if (File.Exists(filePath))
{
Debug.Log("file exist");
string dataAsJson = File.ReadAllText(filePath);
JsonUtility.FromJsonOverwrite(dataAsJson, LocalizationData.localizedText);
}
else
{
Debug.LogError("Cannot find localization file!");
}
}
public void SaveLocalizedText()
{
string filePath = Path.Combine(Application.streamingAssetsPath, fileName + ".json");
string jsonData = JsonUtility.ToJson(LocalizationData.localizedText);
File.WriteAllText(filePath, jsonData);
}
Trying to read a json file from my streaming assets folder gives me this issue in my android build.
Code responsible:
public static Level Load(string file) {
string filePath = Path.Combine("Levels", file);
Debug.Log($"Loading level {filePath}");
string jsonString = BetterStreamingAssets.ReadAllText(filePath);
Level deserialized = JsonConvert.DeserializeObject<Level>(jsonString);
return deserialized;
}
The file is located in StreamingAssets/Levels
Unity version: 2018.3.5f1 Personal
Android version: 9
Phone: OnePlus 6
This works in the editor, but on a build for the Oculus Quest it returns false. Any ideas what I am doing wrong? The files in the folder are of the following naming scheme:
localization/english/cards-core.csv
var folderPath = Path.Combine("localization", language);
if (!BetterStreamingAssets.DirectoryExists(folderPath))
{
this.LogWarning($"Localization folder not found for {language}");
return;
}
As an additional test, I added in the following lines of code. In the editor it finds two files, in the Oculus Quest build it returns 0:
string[] paths = BetterStreamingAssets.GetFiles("/", "*.csv", SearchOption.AllDirectories);
this.Log($"Found {paths.Length} files");
your example on main page not work ( seek from end ):
// as stream, last 10 bytes
byte[] footer = new byte[10];
using (var stream = BetterStreamingAssets.OpenRead("Foo/bar.data"))
{
stream.Seek(footer.Length, SeekOrigin.End); // cursor will be on wrong position ( over of file )
stream.Read(footer, 0, footer.Length);
}
Hi,
I recently noticed my app throwing an exception during startup when using the builtin Unity patch functionality. It allows patching the previously installed app for faster development (link). In short a blob with updated binary data is injected into the startup process, so to say.
This collides with your plugin around here. The blob file is provided instead of the APK and can't be read due to missing privileges of some sort.
I circumvented it for the time beeing by adding a check for the path extension but maybe you can come up with something more universal.
How can I load a image stack from steaming asses?
hello,
I need to load ZipArchive from the streamingAsset folder.
Is there an important reason for blocking this feature?
Do i need to change folder name in Streaming Assets to lowercase ?not filename
This does not work in webgl for me.
FileNotFoundException: File not found at BetterStreamingAssets.ThrowFileNotFound (System.String path) [0x00000] in <00000000000000000000000000000000>:0
Was it supposed to work in webgl?
Also - can you help me with a specific project?
Hi! I'm trying to load an Audio using this library. Is there any implemented way to do it or should I try to find a way to convert byte array to audioclip ?
Thanks in advantage.
The unity API Application.dataPath return the splited apk filename like this:
/data/app/~~3CG-FFhALRftRfz3SRlP5w==/com.xxx.xxx.android-_teRGWyYbrKiCvOn6kdK4g==/split_UnityDataAssetPack.config.other_countries.apk。
so the GetStreamingAssetsInfoFromJar function gathering the files in the splited apk files, the master asset file is not collected.
use bundletool extract-apks will get the splited apks of device specified apks:
base-arm64_v8a_2.apk
base-master_2.apk
UnityDataAssetPack-master.apk
UnityDataAssetPack-other_countries.apk
The UnityDataAssetPack is the name of install-time asset pack name.
The other_countries can be countries set name if specificed, so the UnityDataAssetPack-other_countries.apk
can be other name like: UnityDataAssetPack-countries_latam.apk or UnityDataAssetPack-countries_na.apk
I use adb shell ls command to list the files in the install directory of devices:
BTW install-time asset pack can more than one.
Hi there,
Firstly, thank you so much for making this code available for public use, I'm already so blown away with being able to browse my own APK in this manner, it'll be so much better for debugging and copying things! :)
This could be an issue on my side, but I was wondering if you'd happen to know anything about System.UriFormatException when pressing the "Test Selected Paths" button in the example scene?
The scene loads my APK flawlessly and merrily lists the StreamingAssets content, but then immediately returns this message when I press "Test":
System.UriFormatException: Invalid URI: The format of the URI could not be determined.
at System.Uri.CreateThis (System.String uri, System.Boolean dontEscape, System.UriKind uriKind) [0x0007b] in <6d7c4c8dd3624dc596686fb7270ae1e6>:0
at System.Uri..ctor (System.String uriString) [0x00014] in <6d7c4c8dd3624dc596686fb7270ae1e6>:0
at Better.StreamingAssets.BSA_TestSceneGUI.get_StreamingAssetsPath () [0x00016] in C:\Users\adamc\Documents\Unity3D\CWLCommissioner\Assets\Plugins\BetterStreamingAssets\BSA_TestSceneGUI.cs:225
at Better.StreamingAssets.BSA_TestSceneGUI+<TestHarness>d__29.MoveNext () [0x00079] in C:\Users\adamc\Documents\Unity3D\CWLCommissioner\Assets\Plugins\BetterStreamingAssets\BSA_TestSceneGUI.cs:386
at Better.StreamingAssets.BSA_TestSceneGUI+<ErrorCatchingCoroutine>d__28.MoveNext () [0x0003b] in C:\Users\adamc\Documents\Unity3D\CWLCommissioner\Assets\Plugins\BetterStreamingAssets\BSA_TestSceneGUI.cs:365
UnityEngine.Debug:Log (object)
Better.StreamingAssets.BSA_TestSceneGUI/<>c__DisplayClass26_0:<TestAllCoroutine>b__1 (System.Exception) (at Assets/Plugins/BetterStreamingAssets/BSA_TestSceneGUI.cs:314)
Better.StreamingAssets.BSA_TestSceneGUI/<ErrorCatchingCoroutine>d__28:MoveNext () (at Assets/Plugins/BetterStreamingAssets/BSA_TestSceneGUI.cs:369)
UnityEngine.MonoBehaviour:StartCoroutine (System.Collections.IEnumerator)
Better.StreamingAssets.BSA_TestSceneGUI/<TestAllCoroutine>d__26:MoveNext () (at Assets/Plugins/BetterStreamingAssets/BSA_TestSceneGUI.cs:303)
UnityEngine.MonoBehaviour:StartCoroutine (System.Collections.IEnumerator)
Better.StreamingAssets.BSA_TestSceneGUI:OnGUI () (at Assets/Plugins/BetterStreamingAssets/BSA_TestSceneGUI.cs:179)
It's very possible there's an issue with my pathing - I've tried lowercasing everything, removing spaces etc, but am unsure if there's anything I can try?
I popped in a debug.log for path just before it tries to load a file, and it comes back with
Attempting to read 'cwltwo/arenasetup.txt'
It looks like this local path is right from reading the lovely clear documentation (seriously, thank you, it's been a treat to use your work!), but wasn't sure if it's a Unity issue or something remarkably daft i've not done on my side?
If it helps, I'm using Unity 2021.3.2f1 (LTS) and have tried to this process in 2020.3.19f1 also.
Edit (again!): sorry, I just realised I forgot to note that the issue is for all the Read and Test Modes, and I've played around with the repetition count.
Thank you for your time :)
Hy!
I can easily get a file from StreamingAssets like this:
return BetterStreamingAssets.ReadAllText("config.json");
But how can I save a file? This piece of code not working on android:
File.WriteAllBytes($"{BetterStreamingAssets.Root}\\Contents\\{content.Id}.ref", refResponse.ReadAsByteArray());
OpenHarmony is a new mobile operating system, which has already been supported by TuanJie Engine of Unity. And the BetterStreamingAssets needs some platform adaptation codes to support it as well. So could i submit these codes to this repository? I have completed the functional testing. The code example is as follows:
public static void Initialize(string dataPath, string streamingAssetsPath)
{
#if UNITY_OPENHARMONY
dataPath = "/data/storage/el1/bundle/entry.hap";
#endif
... ... ... ...
when im loading pictures on desktop everything works fine but after porting to apk i see only white
I'm getting a System.IO.FileNotFoundException: File not found
exception when using the plugin on the Oculus Quest. I have verified that the files exist in the StreamingAssets directory, and are included in the APK. The code works correctly in the Editor.
I am calling GetFiles() to get a list of all my StreamingAssets files and folders - to do so I copied the xample code from the repository readme and changed it for my use case:
string[] paths = BetterStreamingAssets.GetFiles("\\", "*", SearchOption.AllDirectories);
- it worked just fine on the editor, but on Android I got this exception:
DirectoryNotFoundException: Attempted to access a path that is not on the disk.
at BetterStreamingAssets+ApkImpl.GetFiles (System.String path, System.String searchPattern, System.IO.SearchOption searchOption) [0x00190] in <697df9379d4040eeb82e91f9e9d87c04>:0
at BetterStreamingAssets.GetFiles (System.String path, System.String searchPattern, System.IO.SearchOption searchOption) [0x00000] in <697df9379d4040eeb82e91f9e9d87c04>:0
I found that it would work if I changed the "\" path argument to a foward slash "/" it seemed to fix it, but then I noticed that it would only return the files in the topmost folder (in this case, the StreamingAssets folder root.
Here's my StreamingAssets folder contents:
│ assays.json
│ assays.json.meta
│ graphics.meta
│ test.json
│ test.json.meta
│
└───graphics
0001.png
0001.png.meta
0002.png
0002.png.meta
0003.png
0003.png.meta
0004.png
0004.png.meta
0005.png
0005.png.meta
0006.png
0006.png.meta
0007.png
0007.png.meta
0008.png
0008.png.meta
Only the 2 .json files are returned - If I do copy those .png files to the root folder then they are returned as well.
Moreover, if I try and call GetFiles()
on the graphics folder, it throws DirectoryNotFoundException
no matter what I put in the path - I tried "graphics", "/graphics", "\graphics", "graphics" and so on - nothing really worked.
Using Unity 2019.2.18f, and a device on Android 8.
Hey,
I am new to this, and I wonder how can I access the folder path in streamingAssets after building in Android from Unity? I have a NLP model storing in streamingAssets, and I need the path to run it in Android device. How can I use BetterStreamingAssets to approach it?
Thanks in advance for your help!
The program to retrieve files from Assets/StreamingAssets using this plugin works on PC and IOS, but not on android. I have also installed a workaround program for android, but it has some errors. (If I write as instructed, /Users/MyName/ProjectName/Assets/Plugins/BetterStreamingAssets/BetterStreamingAssetsCustom.cs(24,24): Error CS0759: No Defining declaration found for implementing declaration of partial method 'BetterStreamingAssetscustom.AndroidIsCom AndroidIsComCom': Error CS0759: No defining declaration found for implementing declaration of partial method 'BetterStreamingAssetscustom.AndroidIsComCom' (CS0759). It is possible that I have put the workaround program in the wrong way, but I would like to solve the problem if possible, please advise. Thanks for your support.
not worked on assetbundle with offset
Hi,
Thank you for your very handful plugin :)
I'm just disappointed because I wanted to use it on my project as-is, without modification, but I need to set position on a SubReadOnlyStream, which can be done as it can seek. But SubReadOnlyStream throws when trying to set position. Why ?
I would suggest replacing the NotSupportedException throw by something like this : m_position = m_offset + value;
Also you have a double semicolon line 57 in the same class.
Thanks !
It's odd but running the application build and run will work but when uploaded to google play and delivered it seems like betterstreamingassets can't find any files.
I'm not getting any crash or error, it's just simply not finding any files when served from Google leading me to think their apk generation maybe moves the location?
How to read .xml file from streamingassets folder? So that I can read haarcascade_frontalface_default.xml file from that folder.
As in the example of the asset, using the GetFile() with the "\" path returns a "Directory not found exception" . (Line 389)
Changing the code to this:
string sep = Path.DirectorySeparatorChar.ToString();
string[] paths = BetterStreamingAssets.GetFiles(sep+sep, "*.xml", SearchOption.AllDirectories);
solves the issue.
Hi there,
Hopefully, I am in the correct place to ask for help with my issue.
Currently, I'm building a VR application using Meta Quest 3 VR glasses. One of the important aspects of the application is that certain objects need to be loaded during runtime and be accessible from the outside (outside the editor (e.g. file explorer)). In the editor, I do this using the StreamingAssets folder and an OBJLoader called Runtime OBJ Importer. In the editor, everything works fine and dandy, but when I upload my APK build to the glasses, it seems that no files get found and thus no files get loaded in.
here's the code that differentiates between the Unity Editor and the APK: (GitHub for some reason doesn't show code insert correctly (sorry))
`
void Start()
{
BetterStreamingAssets.Initialize();
Debug.Log("Getting all files..." + BetterStreamingAssets.GetFiles("\")); // Log message indicating file gathering process
if (Application.platform == RuntimePlatform.Android)
{
filesArray = BetterStreamingAssets.GetFiles("\\", "*.*", SearchOption.AllDirectories);
Debug.Log("Getting all files..." + BetterStreamingAssets.GetFiles("\\")); // Log message indicating file gathering process
}
else
{
filesArray = Directory.GetFiles(Application.streamingAssetsPath, "*.*", SearchOption.AllDirectories); // List to store file names
Debug.Log("Getting all files..." + Application.streamingAssetsPath); // Log message indicating file gathering process
}
files = new List<string>(filesArray);
Containers = new GameObject[filesArray.Length];
Trash = new GameObject[filesArray.Length];
for (int i = 0; i < files.Count; i++)
{
Debug.Log(files[i]);
}
RemoveDuplicatesAndMeta();
AssignObjToArray();
}
`
EDIT: Using "/" instead of "double \" now returns file paths. Unfortunately, I need the full root of the folders as well... (e.g. /data/app/~~4rWYwDQq-8wtLaJsyFF-LA==/com.FAT100.StarterApp-uBE16dDsV0WzTAOYTjcMiQ==/base.apk/assets/...)
I am unable to hardcode this since the characters after "squiggly line" are not static (every build has different chars and so when I update the chars differ again).
Is there any way to return the full path to specific files?
What I'm wondering is how I can correctly return the file paths (which I need to load in objects using Runtime OBJ Importer) of the files that I place in the StreamingAssets folder while running the APK on the Meta Quest 3 VR glasses.
When using an APK editor application I see my files correctly and in the correct folders. The only different thing is the tool folder which is now called 'assets'. (see image)
Another side note: I saw that reading files from APK is a bit funky, but when you use lower-case it should be fine, after building the APK, some files automatically get renamed using upper-case letters for some reason...
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.