最简单的案例代码,备后需使用
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using UnityEngine;
using System.Reflection;
using System.IO;
using System;
/// <summary>
/// 加载web代码
/// </summary>
public class LoadWebScript : MonoBehaviour {
static LoadWebScript _instance;
public static LoadWebScript Instance {
get
{
if (_instance != null)
{
return _instance;
}
else {
GameObject g = new GameObject("LoadWeb");
return g.AddComponent<LoadWebScript>();
}
}
}
/// <summary>
/// 代码网络地址
/// </summary>
public string NetPath {
get {
XmlDocument doc = new XmlDocument();
doc.Load(Application.streamingAssetsPath+ "/WebConfig/webconfig.xml");
XmlElement list= doc.DocumentElement;
XmlElement ele = (XmlElement)list.SelectSingleNode("remote");
string path = ele.GetAttribute("path");
if (string.IsNullOrEmpty(ScriptSpaceName)) {
ScriptSpaceName = ele.GetAttribute("script");
}
return path;
}
}
private string ScriptSpaceName;
private string ScriptFullName {
get {
return ScriptSpaceName + ".dll";
}
}
private string OutScriptPath {
get {
return Application.streamingAssetsPath + "/OutScript/";
}
}
private void Awake()
{
StartCoroutine(UpdateScript());
}
IEnumerator UpdateScript() {
print(NetPath);
WWW www = new WWW(NetPath+"/"+ScriptFullName);
yield return www;
if (www.error != null)
{
Debug.LogWarning(www.error);
Load();
}
else
{
StartCoroutine(SaveScript(www.bytes,Load));
}
}
IEnumerator SaveScript(byte[] b,Action act) {
FileStream fs = File.Open(OutScriptPath+ScriptFullName, FileMode.Create);
fs.Write(b, 0, b.Length);
yield return fs;
fs.Close();
act.Invoke();
}
private void Load()
{
if (File.Exists(OutScriptPath + ScriptFullName))
{
print(OutScriptPath + ScriptFullName);
byte[] _byte = File.ReadAllBytes(OutScriptPath + ScriptFullName);
print(_byte.Length);
Assembly Ass = Assembly.Load(_byte);
Type t = Ass.GetType(ScriptSpaceName + ".OutManager");
print(ScriptSpaceName + ".OutManager");
print(t);
MethodInfo m = t.GetMethod("Main");
m.Invoke(null, null);
}
}
}