Hello im using the following script to fill a json with some data from a open source API and when i try to load the data into a List it gives me a “IOException: Sharing violation on path” + my path. And i don’t know wat is happening.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.IO;
public class APICall : MonoBehaviour
{
readonly string url = "https://opentdb.com/api.php?amount=10&category=10&difficulty=easy&type=multiple";
public List<QuestionItem> questions_;
void Awake()
{
StartCoroutine(SimpleWebRequest());
}
private void Start()
{
string path = Application.persistentDataPath + "/" + "questions.json";
string loadedquestion = JSONUtility.LoadJsonAsExternalResource(path);
QuestionItem myloadedQuestion = JsonUtility.FromJson<QuestionItem>(loadedquestion);
questions_.Add(myloadedQuestion);
}
IEnumerator SimpleWebRequest()
{
UnityWebRequest apiRequest = UnityWebRequest.Get(url);
yield return apiRequest.SendWebRequest();
if (apiRequest.isNetworkError || apiRequest.isHttpError)
{
Debug.Log(apiRequest.error);
}
else
{
JSONUtility.WriteJsonToExternalResources("questions.json", apiRequest.downloadHandler.text);
}
}
}
QuestionItem Script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class QuestionItem
{
public string question;
public string correct_answer;
public string[] incorrect_answers;
public string type;
public string difficulty;
public string category;
}
JSONUtilities Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
public class JSONUtility
{
public static string LoadJsonFromFile(string path, bool isResource)
{
if (isResource)
{
return LoadJsonAsResource(path);
}
else
{
return LoadJsonAsExternalResource(path);
}
}
public static string LoadJsonAsResource(string path)
{
string jsonFilePath = path.Replace(".json","");
TextAsset loadedJsonFile = Resources.Load<TextAsset>(jsonFilePath);
return loadedJsonFile.text;
}
public static string LoadJsonAsExternalResource(string path)
{
if (!File.Exists(path))
{
Debug.Log("File not found");
return null;
}
StreamReader reader = new StreamReader(path);
string response = "";
while (!reader.EndOfStream)
{
response += reader.ReadLine();
}
return response;
}
public static void WriteJsonToExternalResources(string path,string content)
{
path = Application.persistentDataPath + "/" + path;
FileStream stream = File.Create(path);
byte[] contentBytes = new UTF8Encoding(true).GetBytes(content);
stream.Write(contentBytes,0,contentBytes.Length);
}
}
That everything im using in this problem.
Thank you for your time.