How Do I Read and Write Data From a Textasset File

Moving-picture show yourself at the academy's library, property a heavy yard-folio Calculus book on your hands for most two hours. Tell me, how would that experience on your arms? Hither'due south the thing: that'south exactly what Unity is doing by default to your operating system with all your text files. Here's the more lightweight solution:Unity Addressables TextAsset loading.

In this blog mail, you'll learn how to:

  • What'southward thememory riskthat large text files pose to developing your Unity game
  • How toefficiently reference and manage large text files in Unity before it'due south too late

Maybe you've been in this situation.

Or mayhap you lot haven't yet, merely you lot will.

Handling large text files is a bit problematic in Unity. What happens under the hood is justbesides implicit...

Many developers are unaware of the memory implications of using big text files in Unity.

In any case, there are unlike means to handle text files in Unity, and some are plain worse than others.

Permit's see them.

Quick Navigation

The Traditional Ways to Load Text Files

Using Unity Addressables with TextAssets

Become the Projection Now

The Traditional Ways to Load Text Files

Games love text files.

From pocket-size configuration files to huge XML databases that concur game items that you generated with an external tool.

Some developers fifty-fifty use JSON files to back up game localization.

No matter the reason, many game developers adopt to work with text files for certain subsystems of their games. What they do next is to import these text files into Unity and and so get them loaded into memory...somehow.

In Unity, there are several ways you can load text files into memory. Sorted from least desirable to well-nigh desirable:

  • TextAsset API + Resources API. You place your text in the resources directory and you load it with the Resources API. The problem? You shouldn't be using the Resource directory. It's considered bad exercise for anything bigger than a small-scale configuration file
  • TextAsset API. You can likewise put your text file somewhere inside your assets directories. Then, you make a direct reference out of it in whatsoever of your scripts. This is the most usual way of doing it. The problem? This automatically increases retention consumption and loading times there where it'south referenced, as you'll run across in the image below
  • FileReader API + StreamingAssets. The text files you put inStreamingAssetsland in your final build packages as you lot put them without whatsoever processing. This means you'll have to put extra transmission work to read them, e.yard. by using theC# FileReader API. The main trouble is that you'll end up with hardcoded paths... and we know how stable these paths are

TextAsset: Nasty Memory Consumption

TextAsset: Nasty Retentiveness Consumption

While reading text files fromStreamingAssetson need is fine, sometimes it'south but nice if nosotros tin let Unity help us a chip through references and itsTextAsset API. And as you might argue, it's improve to avert hardcoded paths such every bitStreamingAssets/MyEpicWeapons.xml

What we want is to leverage theretention efficiency of StreamingAssetswith the power ofUnity references.

Surprise! We can easily practise this with Unity Addressables + TextAsset processing.

Using Unity Addressables with TextAssets

Here'due south the process:

  1. Put your text file somewhere in your Assets directory
  2. Marking the text file as addressable nugget
  3. (Optional: set the addressable group toLZMAcompression for best results)
  4. Brand anindirect reference to information technology
  5. Load/Unload it as usual with a combination of the addressables and TextAsset APIs

Easy.

Since I've done already quite many tutorials on this, I won't go in detail on the steps but on the last ane. For more information, read my Unity Addressables Tutorial and/or download this unity projection here.

Allow's create a script that loads the file, prints its length to the panel and then unloads it.

Read the code forPrintAddressablesTextLength.cs beneath:

          public course PrintAddressablesTextLength : MonoBehaviour {   [SerializeField] private AssetReference _addressableTextAsset = null;   void Start()   {      _addressableTextAsset.LoadAssetAsync<TextAsset>().Completed += handle =>      {          Debug.Log($"Length: {handle.Result.text.Length}");          Addressables.Release(handle);      };    } }        

It can hardly exist simpler.

Every bit before long as y'all add this script to any game object, yous'll be able to assign anindirect reference pointing to anyTextAssetfile in your Assets directory. On Start, yous'll run across how it automatically prints the length of the text file for y'all.

The chief benefit of this approach is that yous pay the memory and loading times on demand, while the traditional road of assigning direct references makes youpay by default.

To go a step further, you can create an addressable grouping for text files that useLZMAcompression. This algorithm is very suitable for text equally I bear witness in my Unity Addressables Compression Benchmark.

Addressables TextAsset: LZMA Group Compression

Addressables TextAsset: LZMA Group Compression

Doesn't it feel better now that y'all left the calculus volume on the bookshelf to hold it simply when you really need it?

Go the Project At present

And see in action how to load the addressable json file throughLZMAcompression.

jamesasher1997.blogspot.com

Source: https://www.gamedeveloper.com/disciplines/don-t-let-sneaky-text-assets-and-jsons-crash-your-game

0 Response to "How Do I Read and Write Data From a Textasset File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel