在Unity中,如何以可在Android上运行的方式从json文件填充此allRoundData数组? [英] In Unity, how can I populate this allRoundData array from a json file in a way that works on Android?

查看:74
本文介绍了在Unity中,如何以可在Android上运行的方式从json文件填充此allRoundData数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Unity和Android开发的新手,但是请不要将其标记为重复-我已经在堆栈中寻找了答案,但是类似的主题和问题并未产生任何可行的解决方案,或者想要细节,或者已经过时,或者似乎不适合我的特定需求.

I am new to Unity and Android development, but please do not mark this as a duplicate - I've looked all over the stacks for an answer to this, but similar topics and questions haven't yielded any working solutions, or are wanting on details, or outdated, or seem not to fit my specific need.

好的,我有一个根据以下第1部分和第2部分构建的测验应用程序. 本教程中的2.该链接包含任何人可能需要参考的所有源文件,并且在ios和统一编辑器fyi中一切正常.

Ok, I have a quiz app built from following part 1 & 2 of this tutorial. That link contains all the source files anyone might need for reference, and everything works fine on ios and in the unity editor, fyi.

问题出在Android中的DataController脚本中的loadGameData函数.同样,在iOS和统一编辑器中一切正常,但是当我制作一个Android SDK时,测验为空白,控制台显示无法加载数据. 该函数的当前编写方式(教程链接中的完整文件):

The trouble is with the loadGameData function from the DataController script in Android. Again, everything works fine in iOS and the unity editor, but when I make an Android sdk, the quiz is blank and the console says the data couldn't be loaded. Here is how the function is currently written (full file in tutorial link):

    private void LoadGameData ()
{
    string filePath = Path.Combine (Application.streamingAssetsPath, gameDataFileName);


    if (File.Exists (result)) 
    {
        string dataAsJson = File.ReadAllText (result);
    GameData loadedData = JsonUtility.FromJson<GameData> (dataAsJson);

    allRoundData = loadedData.allRoundData;

    }  // #if(File.Exists...

    else 
    {
    Debug.LogError ("Cannot load game data!");
    }  // #else

} // #LoadGameData

如果您查看 YouTube上的同一教程,则会看到很多人们已经注意到Android版本存在相同的问题,并且没有得到答案.统一论坛也是如此-这就是为什么我不认为这个问题是重复的,并且可能对类似情况的其他人有所帮助的原因之一.

If you check the same tutorial on youtube, you'll see lots of people have noted the same problem with the Android build and have been left unanswered. Same goes with unity forums - that's one reason why I don't think this question is a duplicate and could be helpful to others in a similar situation.

我发现Android对此一直很棘手,并且过去习惯于使用不同的方式来访问基于平台的文件,但是如今,"Application.streamingAssetsPath"应该可以在任何平台上找到流媒体资源目录,甚至Android.

I've found that Android has always been sorta tricky with this and that there used to different ways of accessing a file based on platform, but these days "Application.streamingAssetsPath" should find the streaming assets directory on any platform, even Android.

我还了解到,在android中,即使路径正确,文件也会被压缩,并且只会返回一个url.因此,需要使用unity的WWW类转换该url.我知道了,但是到目前为止,我还无法重新编写loadGameData函数以使其正常工作并加载allRoundData数组.

What I've also learned is that in android, even if the path is correct, the file is compressed and will only return a url. So the url needs to be converted using unity's WWW class. I get that, but as of yet, I haven't been able to re-write my loadGameData function to work properly and load the allRoundData array.

这是我尝试过的一些事情的一个例子:

Here's an example of some things I've tried:

IEnumerator androidData() 
{
    string filePath = Path.Combine (Application.streamingAssetsPath, gameDataFileName);
    if (filePath.Contains("://")) 
    {
        WWW www = new WWW(filePath);
        yield return www;
        result = www.text;
    } // #if(filePath.Contains
} // #androidData


private void LoadGameData ()

{

    androidData();


    if (File.Exists (result)) 
    {

        string dataAsJson = File.ReadAllText (result);
    GameData loadedData = JsonUtility.FromJson<GameData> (dataAsJson);

    allRoundData = loadedData.allRoundData;

    }  // #if(File.Exists...
    else 
    {
    Debug.LogError ("Cannot load game data!");
    }  // #else
} // #LoadGameData

我知道我已经接近了,这可能很简单-但我似乎无法达到终点.有人可以帮我弄清楚如何编写loadGameData函数,以便它将在Android上加载此allRoundData数组吗?

I know I'm close, and this is probably simple -- but I just can't seem to get to the finish line on this. Can some one help me figure out how to write the loadGameData function so it will load this allRoundData array on android?

一个示例代码将是很棒的,并且非常感谢,不仅是我自己,而且我敢肯定,很多其他人也会喜欢它-谢谢!

An example code would be awesome and much appreciated, not just by me, but I'm sure many others would appreciate it also - Thank you!

更新: 基于第一个答案,我测试了一些可在统一编辑器上运行的代码,但在Android中崩溃.在Unity编辑器中,我收到文件已存在"消息.这是我测试过的代码: 已经有:private string gameDataFileName = "data.json"; 我在Start()的loadGameDate上方添加了copyFile调用,并编写了复制文件和loadGameData函数,例如..

UPDATE: Based on the first answer, I've tested some code that works on the unity editor, but crashes in Android. In the Unity editor, I get the "file already exists" message. Here is the code I've tested: Already had: private string gameDataFileName = "data.json"; I added the copyFile call above loadGameDate in Start() and wrote the copy file and loadGameData functions like so ..

int copyFileToPersistentDataPath(string gameDataFileName)
{
    string persistentPath = Application.persistentDataPath + "/" + gameDataFileName;

    try
    {
        //Copy only if gameDataFileName does not exist  
        if (!System.IO.File.Exists(persistentPath))
        {
            string path = System.IO.Path.Combine(Application.streamingAssetsPath, gameDataFileName);
            WWW www = new WWW(path);
            while (!www.isDone) { }
            System.IO.File.WriteAllBytes(persistentPath, www.bytes);
            Debug.Log(gameDataFileName + " Successfully Copied File to " + persistentPath);
            return 1;
        }
        else
        {
            Debug.Log(gameDataFileName + " File already exist here. There is no need to copy it again");
            return 0;
        }
    }
    catch (Exception e)
    {
        Debug.Log(gameDataFileName + " Failed To Copy File. Reason: " + e.Message);
        return -1;
    }
}



private void LoadGameData ()
{


    string tempPath = Path.Combine(Application.persistentDataPath, gameDataFileName);

    string dataAsJson = File.ReadAllText(tempPath);
    GameData loadedData = JsonUtility.FromJson<GameData>(dataAsJson);
    allRoundData = loadedData.allRoundData;
    } // #LoadGameData

无论是否调用在编辑器中复制文件,此方法都可以使用,但在Android中都会崩溃.

This works with or without the call to copy the file in the editor, but crashes either way in Android.

推荐答案

我最终将文件放在Resources文件夹中,然后转到资源.将json文件加载到文本资产中,然后将其放入字符串中以解析路由.我现在有两种不同的加载功能,一种可以在ios等中运行,另一种可以在android中运行.这是android函数(resourcesGameDataFile不具有.json扩展名):

I ended up putting the files in a Resources folder and going the resources.load a json file into a text asset and throw that into a string to parse route. I now have two different load functions, one that works in ios etc. and one that works in android. Here is the android function (the resourcesGameDataFile does not have the .json extension):

public void LoadDataForAndroid()
{

    TextAsset dataFile = Resources.Load(resourcesGameDataFile) as TextAsset;
    string dataAsJson = dataFile.ToString();
    GameData loadedData = JsonUtility.FromJson<GameData>(dataAsJson);
    allRoundData = loadedData.allRoundData;
    Debug.Log ("Android data loaded with" + resourcesGameDataFile);
} // #LoadDataForAndroid

这可以在unity编辑器和Bluestacks(Android模拟器)中使用.

And this works in the unity editor and in Bluestacks (android simulator).

这篇关于在Unity中,如何以可在Android上运行的方式从json文件填充此allRoundData数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆