Unity在编辑器中工作而不在设备上。加载本地存储的远程JSON,然后填充下拉列表

时间:2017-04-11 12:38:09

标签: c# android json unity3d

所以我在远程json文件中加载,在本地存储然后读取本地文件以填充最终插入到屏幕下拉列表中的列表。我尝试了各种各样的事情,使用litjson并使用application.various路径处理错误。

无论如何,我最终得到了所有工作,但只在编辑器中,我在屏幕上弹出一个名为Debug的文本框,在屏幕上加载文本,它应该显示文件的内容,它在编辑器中但不在我的android上设备

我更改了所有文件夹路径以移动并将所有内容加载到资源文件夹,因为我读到这可能是一个问题。

将代码更改为writer而不是litjson writealltext(),毕竟我的结果相同。

它在统一中工作但不在设备上工作,就像populateList()函数没有触发一样。

我被困住了。帮助赞赏。

下面是代码:

using UnityEngine;
using System.Collections;
using LitJson;
using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine.UI;

public class loadJSONFoodCats : MonoBehaviour {

    public string url;
    private string jsonString;
    private JsonData itemData;
    public List<Category> myListCats = new List<Category>();
    private List<string> catTags = new List<string>();

    public Dropdown typeFilter;

void Start (){
      WWW www2 = new WWW(url);
      StartCoroutine(WaitForRequest(www2));
}

IEnumerator WaitForRequest(WWW www2){
  yield return www2;

  // check for errors
  if (www2.error == null)
  {
    //SAVE JSON FROM ONLINE LOCALLY
        jsonString = www2.text;
        string path = "Assets/Resources/JSON/FoodnDrinkCats.json";
        string str = jsonString;
         using (FileStream fs = new FileStream(path, FileMode.Create)){
             using (StreamWriter writer = new StreamWriter(fs)){
                 writer.Write(str);
             }
         }

       // Debug.Log("PASSED");

    //READ SAVED FILE
        TextAsset file = Resources.Load("JSON/FoodnDrinkCats") as TextAsset;

    jsonString = file.ToString();
    itemData = JsonMapper.ToObject(jsonString);

    //SORT DATA OUT
        ConstructCatsDatabase();
        //Debug.Log(myList[0].post_title);

        //Category cat = fetchItemByID(255);
        //listing.post_title;
        //Debug.Log(cat.Slug);
        Text singleText = GameObject.Find("Debug").GetComponent<Text>();
        singleText.text = "LOADING:"+myListCats[0].Name;

        populateList();

      } else {
      Debug.Log("WWW Error: "+ www2.error);
      }    
  }

    void ConstructCatsDatabase(){

        for (int i = 0; i < itemData.Count; i++) {
            myListCats.Add(new Category((int)itemData[i][0], itemData[i][1].ToString(), itemData[i][2].ToString()));
        }

  }

    public Category fetchItemByID(int id){

        for (int i = 0; i < myListCats.Count; i++) {
            if(myListCats[i].Term_ID == id){
                return myListCats[i];
            }

        }
        return null;
 }


    void populateList(){
        for (int i = 0; i < myListCats.Count; i++) {
            //TRANSLATION DONE, NOW ADD THEM
            catTags.Add(myListCats[i].Name);

            Text singleText = GameObject.Find("Debug").GetComponent<Text>();
            singleText.text = "info:"+myListCats[i].Name;
        }
        catTags.Sort();
        typeFilter.AddOptions(catTags);



    }



}




public class Category {

    public int Term_ID {get; set;}
    public string Name {get; set;}
    public string Slug {get; set;}

    public Category(int id, string name, string slug){

        this.Term_ID = id;
        this.Name = name;
        this.Slug = slug;

    }

}

3 个答案:

答案 0 :(得分:1)

中,你不能轻易地写入FileSystem。那里有一个叫isolated storage的东西。

使用Application.persistentDataPath作为JSON的路径。它建议从Unity3D开始,适用于所有平台。

另请确保您的Android清单文件包含:(位于资产/插件/ Android中)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在Android中检查构建配置以获取写访问权限:

enter image description here

答案 1 :(得分:0)

要在不同平台上书写,请使用Application.persistentDataPath

因此,您的代码路径将成为这样的写作:

string path = Application.persistentDataPath +“FoodnDrinkCats.json”;

答案 2 :(得分:0)

这是解决方案。

此代码将在各种平台上管理文件系统。写入读取和路径管理。到目前为止,它完美无缺。它来自一个名叫FAEZ的人的团结论坛。

public void writeStringToFile( string str, string filename )
{
#if !WEB_BUILD
string path = pathForDocumentsFile( filename );
FileStream file = new FileStream (path, FileMode.Create, FileAccess.Write);

StreamWriter sw = new StreamWriter( file );
sw.WriteLine( str );

sw.Close();
file.Close();
#endif  
}


public string readStringFromFile( string filename)//, int lineIndex )
{
#if !WEB_BUILD
string path = pathForDocumentsFile( filename );

if (File.Exists(path))
{
FileStream file = new FileStream (path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader( file );

string str = null;
str = sr.ReadLine ();

sr.Close();
file.Close();

return str;
}

else
{
return null;
}
#else
return null;
#endif 
}


public string pathForDocumentsFile( string filename ) 
{ 
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
string path = Application.dataPath.Substring( 0, Application.dataPath.Length - 5 );
    path = path.Substring( 0, path.LastIndexOf( '/' ) );
    return Path.Combine( Path.Combine( path, "Documents" ), filename );
}

else if(Application.platform == RuntimePlatform.Android)
{
string path = Application.persistentDataPath;   
path = path.Substring(0, path.LastIndexOf( '/' ) ); 
return Path.Combine (path, filename);
}   

else 
{
string path = Application.dataPath; 
path = path.Substring(0, path.LastIndexOf( '/' ) );
    return Path.Combine (path, filename);
    }
}