-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPluginLoader.cs
87 lines (81 loc) · 2.53 KB
/
PluginLoader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.IO;
using System.Reflection;
using System.Collections;
public class PluginLoader :MonoBehaviour
{
private Assembly assembly;
//! Adds plugins from mods to the game.
public void Start()
{
string modPath = Path.Combine(Application.persistentDataPath, "Mods");
Directory.CreateDirectory(modPath);
string[] modDirs = Directory.GetDirectories(modPath);
foreach (string path in modDirs)
{
string pluginPath = path + "/Plugins/";
Directory.CreateDirectory(pluginPath);
DirectoryInfo d = new DirectoryInfo(pluginPath);
foreach (FileInfo file in d.GetFiles("*.dll"))
{
string filePath = pluginPath + file.Name;
string pluginName = file.Name.Remove(file.Name.Length - 4);
LoadPlugin(pluginName, filePath);
Debug.Log("Loading mod plugin: " + pluginName);
}
}
}
//! Starts the assembly loading coroutine.
private void LoadPlugin(string pluginName, string url)
{
StartCoroutine(LoadAssembly(pluginName, url));
}
//! Uses GetAssembly to load classes from the dll and add them to a dictionary.
private IEnumerator LoadAssembly(string pluginName, string url)
{
if(url == null)
{
yield break;
}
UriBuilder uriBuildier = new UriBuilder(url) { Scheme = "file" };
using (UnityWebRequest uwr = UnityWebRequest.Get(uriBuildier.ToString()))
{
yield return uwr.SendWebRequest();
if (!uwr.isNetworkError && !uwr.isHttpError)
{
assembly = GetAssembly(uwr);
}
}
if (assembly != null)
{
AddPlugin(assembly, pluginName);
}
}
//! Loads assembly from file.
private Assembly GetAssembly(UnityWebRequest uwr)
{
if (uwr != null)
{
if (uwr.downloadHandler != null)
{
if (uwr.downloadHandler.data != null)
{
return Assembly.Load(uwr.downloadHandler.data);
}
}
}
return null;
}
//! Gets type by name from dll.
private void AddPlugin(Assembly dll, string pluginName)
{
Type type = dll.GetType(pluginName);
if (type != null)
{
GameObject obj = new GameObject { name = pluginName };
obj.AddComponent(type);
}
}
}