So, you want to use data from the web in your editor scripts? Well you would have to use coroutines, which are only call-able on MonoBehaviour
s, and since your editor script must inherit from EditorWindow, it can't run coroutines. You have 2 options:
1. Let the whole UI stay stuck until www
returns. This is typically a couple of seconds. You would use something like this:
WWW www = new WWW(webPath);
while(!www.isDone) ;
if(www.error != null) {
Debug.LogError(www.error);
} else {
Debug.Log(www.text);
}
2. Fix it the proper way. In that case you would again have a couple of options:
a) In your Editor script, add a new object to the scene that has a MonoBehaviour
script on it, on which you would call the coroutine and do www yield
. It would have to have [ExecuteInEditMode]
attribute. I don't like this because it dirties the scene after you have cleaned up the object, and my script already works with the scene. It's also very "hacky", to be avoided.
b) Buy a commercial Asset from the asset store.
c) Try your luck with threading. You would still have to access www
members in the thread, so it would probably take some juggling around. Haven't personally tried this approach.
d) Try this solution:
using UnityEngine;
using System;
using UnityEditor;
public class EditorWWW {
private WWW _www;
private Action<string, object[]> _operateWWWResult;
private object[] _arguments;
public void StartWWW(string path, WWWForm form, Action<string, object[]> operateWWWResult, params object[] arguments) {
_operateWWWResult = operateWWWResult;
_arguments = arguments;
if(form != null) {
_www = new WWW(path, form);
} else {
_www = new WWW(path);
}
EditorApplication.update += Tick;
}
public void Tick() {
if(_www.isDone) {
EditorApplication.update -= Tick;
if(!string.IsNullOrEmpty(_www.error)) {
Debug.Log("Error during WWW process:\n" + _www.error);
} else {
if(_operateWWWResult != null) _operateWWWResult(_www.text, _arguments);
}
_www.Dispose();
}
}
public void StopWWW() {
EditorApplication.update -= Tick;
if (_www != null) _www.Dispose();
}
}
Here you subscribe to Editor Update
calls which happen "multiple times per second", but are not regular like game's Update
or FixedUpdate
loop.
If you're finding this article helpful, consider our asset Dialogical on the Unity Asset store for your game dialogues.
Your editor script would call it like this:
WWWForm wwwForm = new WWWForm();
wwwForm.AddField("myField", myField);
EditorWWW editorWWW = new EditorWWW();
editorWWW.StartWWW(_webURL, wwwForm, MyResultOperation);
If you are not sending form data, which is required for getting $_POST
in PHP, or if you are not:
EditorWWW editorWWW = new EditorWWW();
editorWWW.StartWWW(_webURL, null, MyResultOperation);