外部读取json文件(Resources文件外)

由于项目需要客户动态修改json文件来读取相应功能,以前都是Resources.load读取json文件,但是这样打包后无法从外部修改,于是想着用File文件流来读取试试,但是这样做有一个问题,unity会报错说无法在Start或者Awake中读取文件(大致意思),这可难倒我了。。。。。。由于也在做联网项目,突然有了一丝灵感:既然我发在Start或者Awake中读取,我是否可以再开启一个副线程来读取?果然这个方法可行!贴上主要代码:

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

[SerializeField]
/// <summary>
/// 读取json(全程序中第一个执行脚本)
/// </summary>
public class Analysis : MonoBehaviour
{
    string filePath;
    Thread readThread;
     void Awake()
    {
        filePath = Application.dataPath + "/Position.txt";
        readThread  = new Thread(new ThreadStart(Recive));
        readThread.IsBackground = true;
        readThread.Start();
    }
   void Recive()
    {
       
        byte[] buff = File.ReadAllBytes(filePath);//首先用比特流读取文件
        
        string str = Encoding.UTF8.GetString(buff);//读取后转为string
        Save.SavePosition = JsonMapper.ToObject<PositionList>(str);
    }
    void OnDestroy()
    {
        readThread.Abort();
    }
    
}

 

posted @ 2019-03-18 17:40  Cloud_wind  阅读(561)  评论(0编辑  收藏  举报