SanAndreasUnity/Assets/Scripts/Behaviours/PluginManager.cs

74 lines
2.1 KiB
C#
Raw Normal View History

2021-02-19 01:22:03 +00:00
using System;
using System.Collections.Generic;
using System.IO;
2021-02-19 19:35:38 +00:00
using System.Linq;
2021-02-19 01:22:03 +00:00
using System.Reflection;
using SanAndreasUnity.Utilities;
using UnityEngine;
namespace SanAndreasUnity.Behaviours
{
public class PluginManager : MonoBehaviour
{
2021-02-19 19:35:38 +00:00
public abstract class PluginBase
{
}
2021-02-19 01:22:03 +00:00
public static string[] PluginDirectories => new []
{
#if UNITY_EDITOR
2021-02-19 19:35:38 +00:00
Path.Combine(Application.dataPath, $"..{Path.DirectorySeparatorChar}SAU_Plugins"),
2021-02-19 01:22:03 +00:00
#else
2021-03-05 20:55:56 +00:00
Path.Combine(Application.dataPath, "SAU_Plugins"),
2021-02-19 01:22:03 +00:00
#endif
};
2021-03-05 20:55:09 +00:00
void Start()
2021-02-19 01:22:03 +00:00
{
F.RunExceptionSafe(LoadPlugins, $"Error while loading plugins: ");
}
void LoadPlugins()
{
// find all plugins
var allFiles = new List<string>();
foreach (string pluginsDirectory in PluginDirectories)
{
if (!Directory.Exists(pluginsDirectory))
continue;
var filePaths = Directory.GetFiles(pluginsDirectory, "*.dll", SearchOption.TopDirectoryOnly);
// sort files manually to prevent undefined behavior
Array.Sort(filePaths);
allFiles.AddRange(filePaths);
}
int numLoaded = 0;
foreach (string pluginFilePath in allFiles)
{
if (LoadPlugin(pluginFilePath))
numLoaded++;
}
if (allFiles.Count > 0)
Debug.Log($"Loaded {numLoaded}/{allFiles.Count} plugins");
}
bool LoadPlugin(string pluginFilePath)
{
return F.RunExceptionSafe(
2021-02-19 19:35:38 +00:00
() =>
{
var asm = Assembly.LoadFrom(pluginFilePath);
var types = asm.GetTypes();
var pluginTypes = types.Where(t => typeof(PluginBase).IsAssignableFrom(t) && !t.IsAbstract);
pluginTypes.ForEach(t => Activator.CreateInstance(t));
},
2021-02-19 01:22:03 +00:00
$"error loading plugin from '{pluginFilePath}': ");
}
}
}