Hi there,
I’m trying to load a .json file via a custom menu item in the unity editor, and have pretty much fallen at the first hurdle.
I have got as far as opening a file dialog, and getting the path of the json file I want to open, but that’s about it:
[MenuItem ("Custom/Load Map")]
static void start(){
string path = EditorUtility.OpenFilePanel (
"Load Map",
"",
"json");
if (path.Length != 0) {
WWW www = new WWW ("file:///" + path);
Debug.Log (path);
Debug.Log (www)
}
}
I’m just stuck as to where to go from here, I found the following tutorial:
http://blog.paultondeur.com/2010/03/23/tutorial-loading-and-parsing-external-xml-and-json-files-with-unity-part-2-json/
but I can’t get this to be called from the menu item, I think this comes down to my relative lack of experience, and the difference between scripts which are called at runtime, and those that are called by the editor…
A few pointers would be very welcome,
Thanks
Fast forward about ten years later I saw your post and thought it would be useful to answer this for future readers:
public void Apply()
{
#if UNITY_EDITOR
string path = UnityEditor.EditorUtility.OpenFilePanel("your file", "", "txt");
if (path.Length != 0)
{
StartCoroutine(UploadData(path));
}
#endif
}
IEnumerator UploadData(string path)
{
// This is where the data will be stored.
string s;
// When you use "using" it "disposes" data when you go out of the "using" block and frees up the memory
using (UnityWebRequest data = new UnityWebRequest(path, UnityWebRequest.kHttpVerbGET))
{
//A "downloader" for texts would do the job
data.downloadHandler = new DownloadHandlerBuffer();
// downloader sends requests to download the file and stops when the entire data is downloaded
yield return data.SendWebRequest();
//The text can be accessed using the downloader, you can use it for images sounds, and whatnot
s = ((DownloadHandlerBuffer)data.downloadHandler).text;
}
Foo(s); // do whatever you want with the downloaded text file here
}
Why even using a UnityWebRequest or WWW? We’re inside the editor using a local filepath. So reading the content of a local file would be just
[MenuItem ("Custom/Load Map")]
static void LoadMap()
{
string path = EditorUtility.OpenFilePanel ("Load Map", "", "json");
if (string.IsNullOrEmpty(path))
return;
string content = System.IO.File.ReadAllText(path);
// do something with the file content. Since it's about json, probably parse the json.
}