Detail Unity3d (i)--mobile platform dynamic read External file full parsing

Source: Internet
Author: User

Objective:

There has always been an idea, is to work in the pit through their own deep digging into a set of solutions for the same problem for colleagues to shoot brick discussion. Eye Gaze 2015 The first business day is coming, small bastard also rest almost, thinking also should write something activity brain and finger. So today, the small bastard will record some of the usual work encountered in the pit, as well as small bastard coping methods, welcome to shoot brick discussion. So today we are going to focus on how Unity3d dynamically reads external files such as CSV (TXT) and XML files on the mobile side. The main problem is that the PC side of the original test of good things, to the mobile end can not be used, so to discuss the difference between PC and mobile, then the next problem is naturally the mobile side of the resource path (to discuss resources, Streamingassets, Assetbundle, Persistentdatapath), the final step is to find the resources how to read (here will be specific to the corresponding situation, namely, resources, Streamingassets, Assetbundle), The main idea is this. Yes, the preface is still to wish you crossing a new year of physical health, promotion of pay.

If I want to read the file dynamically in the editor

Actual game development, in fact, a considerable part of the static data can be placed on the client, it is bound to generate the need to dynamically read these files, such as CSV (in fact, text files), XML and so on. I believe that we do not use win or Mac to do Unity3d development, must first in the editor to achieve the basic functions, in specific to each mobile platform to debug. So as the first step to read an external file, obviously we have to do this on the editor, which is the PC.

Let me give you an example of reading XML, which I used in an earlier article, "Do it by myself using reflection and generics, dynamically read XML to create class instances and assign values," and dynamically read an XML file and dynamically generate a class.

Here is the XML file we used to do the example, Test.xml:

<?xml version= "1.0" encoding= "UTF-8"?><test>    <name>chenjd</name>    <blog> http://www.cnblogs.com/murongxiaopifu/</blog>    <organization>Fanyoy</organization>    <age>25</age></test>

We can be very willful to leave this file in a place, as long as you can specify the address of it. For example I also put it in the article in the Address assets/xml-to-egg/xml-to-egg-test/folder (it is very willful)

Below we implement the code to read the contents of this file on the PC:

Read the XML test using unityengine;using system.collections;using eggtoolkit;using system.xml.linq;public class test: Monobehaviour {    //Use this for initialization    void Start () {        XElement result = LoadXML ("assets/xml-to-egg/x Ml-to-egg-test/test.xml ");//Willful address        Debug.Log (result. ToString ());    }        Update is called once per frame    void Update () {        }    private  XElement LoadXML (string path)    {
   xelement XML = xelement.load (path);        return XML;    }}

The results are as follows:

The result is a read success. But you think it's a mistake to be successful in this step. Because such code does not work on the mobile side, at least 2 can be scolded SB:

    1. The intoxicating address, the address parameter that writes does not have to consider the cross-platform. So the problem with this SB point is that the target file cannot be found on the mobile side Unity3d.
    2. The use of a traditional set of reading resources on the PC, not using the method provided by Unity3d, so the problem can be caused by finding a file but not the correct read file content.

The above problem is marked with red, that is, small bastard think of the possible problems, but also the content to be discussed below. So let's first look at the differences in the resource paths on each platform.

Resource path problems for mobile platforms

Want to read a file, naturally first to find this file, the following small bastard first will summarize the Unity3d in the existing address, and then summarize the various addresses in each mobile platform corresponding location.

Resource paths in the Unity3d
Application.datapath This property is used to return the path to the folder where the program's data file resides. For example, in editor it is assets.
Application.streamingassetspath This property is used to return the cache directory for stream data, and the return path is relative to the path that is appropriate for setting up some external data files.
Application.persistentdatapath This property is used to return a path to a persisted data store directory where persisted data files can be stored.
Application.temporarycachepath This property is used to return a cached directory of temporary data.

Android Platform
Application.datapath /data/app/xxx.xxx.xxx.apk
Application.streamingassetspath Jar:file:///data/app/xxx.xxx.xxx.apk/!/assets
Application.persistentdatapath /data/data/xxx.xxx.xxx/files
Application.temporarycachepath /data/data/xxx.xxx.xxx/cache

iOS platform
Application.datapath Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/data
Application.streamingassetspath Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/data/raw
Application.persistentdatapath Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/documents
Application.temporarycachepath Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/library/caches

From the above 3 tables, we can see that the path location of DataPath and Streamingassetspath is generally relative to the installation directory location of the program, The path location of the Persistentdatapath and Temporarycachepath is generally the same as the fixed position of the relative system. So now clear the unity3d of the various addresses on different platforms, the next question is coming, that is, my package after the resource how to correspond to these addresses? To know in the PC editor of the default resource file storage path is assets Ah, why will it derive so many paths? So with this question, and small bastard together to carry out the content of the following.

A brief introduction to the types of resources in the Unity3d (Welcome to shoot Bricks):

Small Bastard encountered the general is the following several, Resources, Streamingassets, Assetbundle, Persistentdatapath, the following simple analysis.

Resources:

Appears as a Unity3d folder, that is, if you create a new folder named Resources, the contents of the package will be unconditionally hit in the release package. The characteristics of this simple summary is:

    1. Read-only, which cannot be modified dynamically. So the resources you want to dynamically update are not put here.
    2. Packages the resources within the folder into the. asset file. Therefore, it is recommended to put some prefab, because Prefab will automatically filter out unwanted resources when packaging, which is helpful to reduce the size of the resource bundle.
    3. Mainline preempted.
    4. Resource reads using Resources.load ().
streamingassets:

To talk about Streamingassets, in fact, and resources are quite similar. Same as a read-only unity3d of the reserved folder appears. There is a big difference, though, that the content in the Resources folder is compressed and encrypted when it is packaged. The contents of the Streamingasset folder are then entered into the package intact, so streamingassets is primarily used to store some binary files. Here's a simple summary:

    1. Similarly, read-only is not writable.
    2. It is used primarily to store binaries.
    3. Only the WWW class can be used to read.
Assetbundle:

There are already a lot of introductions about Assetbundle. In short, prefab or binary files are encapsulated as Assetbundle files (also a binary). But there is also a mishap, that is, the mobile side can not update the script. Below is a brief summary of the following:

    1. is a binary type defined by Unity3d.
    2. It's best to encapsulate the prefab into aseetbundle, but it's not the only way to say that the script can't be updated on the mobile? is the script on the prefab that got from Assetbundle not going to work? Not necessarily, as long as this prefab on the local script, you can.
    3. Use the WWW class to download.
Persistentdatapath:

It seems to be just a path, but why take it out of the path and introduce it separately? Because it is really special, this path is readable and writable. And on iOS is the application sandbox, but on Android it can be a sandbox for the program, or it can be sdcard. And when Android is packaged, the Projectsetting page has an option to write Access, and you can set whether its path is sandbox or sdcard. The following is also a simple summary:

    1. Content can be read and written, but only run to write or read. It is not feasible to store data in this path in advance.
    2. No content restrictions. You can read a binary file from streamingasset or read a file from Assetbundle to write to Persistentdatapath .
    3. Write down the files that can be viewed on the computer. can also be cleared away.

Well, little bastard introduced here, you crossing are not also clear some of it? So here's the final step, how to read an external file on the mobile platform.

How to read external files on a mobile platform

The above small bastard reason to introduce resources, Streamingassets, Assetbundle, Persistentdatapath this four east, is because the operation of reading external resources involved in the things no outside of these kinds. Since the use of Unity3d to develop the game, it is natural to use the Unity3d rules of operation, rather than we are on the PC very primitive kind of operation to operate the way. Otherwise, you can write silly code that cannot be used by the mobile side, as demonstrated at the beginning of this article.

The following small bastard to realize the use of resources, Streamingassets, assetbundle to read the process.

Resources:

First we create a new resources directory, and copy the Test.xml we used above into this folder.

We then read the contents of the Test.xml by means of the resources reading method. And the GUI is called to draw the contents of the XML.

Use resources to read xmlusing unityengine;using system.collections;using eggtoolkit;using system.xml.linq;using System.Xml ;p Ublic class Test:monobehaviour {    private string _result;    Use the this for initialization    void Start () {        LoadXML ("Test");    }        Update is called once per frame    void Update () {        }    private void LoadXML (string path)    {        _result = R Esources. Load (Path). ToString ();        XmlDocument doc = new XmlDocument ();        Doc. LOADXML (_result);     }    void Ongui ()    {        Guistyle titlestyle = new Guistyle ();          Titlestyle.fontsize =;          TitleStyle.normal.textColor = new Color (46f/256f, 163f/256f, 256f/256f, 256f/256f);          Gui. Label (New Rect (N, ten, Max),  _result,titlestyle);}    }

Results

Ok,resources Read external resource goal reached!!

Let's continue, this time using the streamingassets to operate.

Streamingassets:

As with the resources, we will create a new Streamingassets folder to store our test.xml files.

However, the previous article has been said that the contents of the Streamingassets folder will not be compressed and encrypted, but put in what is what, so the general is to put binary files, here Small bastard Just do a demo, you in the actual operation do not put the data files directly into this directory packaging.

Using unityengine;using system.collections;using eggtoolkit;using system.xml.linq;using System.Xml;using System.IO;    public class Test:monobehaviour {private string _result;    Use the this for initialization void Start () {Startcoroutine (LoadXML ()); }//update is called once per frame void update () {}///<summary>///As described earlier, Streamingasse    TS can only use WWW to read, or/or if not to use the WWW to read the classmate, do not ask why read streamingassets content.    You can also use Persistendatapath to save content from Streamingassets.        </summary> IEnumerator LoadXML () {string spath= Application.streamingassetspath + "/test.xml";        www www = new www (spath);        yield return www;    _result = Www.text;          } void Ongui () {Guistyle titlestyle = new Guistyle ();          Titlestyle.fontsize = 20;          TitleStyle.normal.textColor = new Color (46f/256f, 163f/256f, 256f/256f, 256f/256f); Gui.    Label (New Rect (n, A, A, ten), _result,titlestyle);}} 

Results

Ok,streamingassets Read external resource goal reached!!

Let's continue, and finally we'll use Assetbundle to do it.

Assetbundle:

Come to Assetbundle, here is not the same as the above two. First we want to test.xml our files into Assetbundle file, because the small bastard use of millet 3 as a test machine, so the Assetbundle platform selection for Andorid.

, we created a assetbundle file and named Textxml. And according to the Convention of putting binary files into the Streamingassets folder, put this assetbundle file into the Streamingassets folder.

So here is the content of reading test.xml from Assetbudle. Directly on the code:

Read xmlusing eggtoolkit;using system.xml.linq;using system.xml;using system.io;public class Test from Assetbundle:        Monobehaviour {private string _result;    Use the this for initialization void Start () {LoadXML (); }//update is called once per frame void update () {} void LoadXML () {Assetbundle        Etbundlecsv = new Assetbundle ();        Read the bundle file placed in the Streamingassets folder string str = Application.streamingassetspath + "/" + "Testxml.bundle";        www www = new www (str);            www = WWW.LoadFromCacheOrDownload (str, 0);        Assetbundlecsv = Www.assetBundle;            String path = "Test";        Textasset test = assetbundlecsv.load (path, typeof (Textasset)) as Textasset; _result = Test.    ToString ();          } void Ongui () {Guistyle titlestyle = new Guistyle ();          Titlestyle.fontsize = 20;          TitleStyle.normal.textColor = new Color (46f/256f, 163f/256f, 256f/256f, 256f/256f); Gui.Label (New Rect (n, A, A, ten), _result,titlestyle); }    }

Results

Ok,assetbundle Read external resource target also reached!!

This allows us to implement several operations that dynamically read external files. Do you crossing see it? Of course, the article hasty, there are a lot of shortcomings, welcome to shoot Brick Discussion ~

If you crossing think the article is well written, then let small bastard you give a "recommendation", Thank you ~

Pretending to be StatementOnce: This Bo article is not special note is original, if need to reprint please retain the original link and author information Murong Small bastard original link: http://www.cnblogs.com/murongxiaopifu/p/4199541.html

Detail Unity3d (i)--mobile platform dynamic read External file full parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.