|
1 | 1 | using IronPython.Hosting; |
2 | 2 | using Microsoft.Scripting.Hosting; |
| 3 | +using System; |
3 | 4 | using System.Collections.Generic; |
| 5 | +using System.Linq; |
| 6 | +using System.Reflection; |
4 | 7 |
|
5 | | -public sealed class UnityPython |
| 8 | +/// <summary> |
| 9 | +/// Convenience class for creating a Python engine integrated with Unity. |
| 10 | +/// |
| 11 | +/// All scripts executed by the ScriptEngine created by this class will: |
| 12 | +/// * Be able to import any class in a `UnityEngine*` namespace |
| 13 | +/// * Be able to import any class in a `UnityEditor*` namespace, if the script |
| 14 | +/// is running in the UnityEditor |
| 15 | +/// </summary> |
| 16 | +public static class UnityPython |
6 | 17 | { |
7 | | - public static ScriptEngine CreateEngine() |
| 18 | + public static ScriptEngine CreateEngine(IDictionary<string, object> options = null) |
8 | 19 | { |
9 | | - return CreateEngine(null); |
10 | | - } |
| 20 | + var engine = Python.CreateEngine(options); |
11 | 21 |
|
12 | | - public static ScriptEngine CreateEngine(IDictionary<string, object> options) |
13 | | - { |
14 | | - ScriptEngine engine; |
15 | | - if (options == null) |
| 22 | + // Load assemblies for the `UnityEngine*` namespaces |
| 23 | + foreach (var assembly in GetAssembliesInNamespace("UnityEngine")) |
16 | 24 | { |
17 | | - engine = Python.CreateEngine(); |
| 25 | + engine.Runtime.LoadAssembly(assembly); |
18 | 26 | } |
19 | | - else |
20 | | - { |
21 | | - engine = Python.CreateEngine(options); |
22 | | - } |
23 | | - |
24 | | - var unityEngine = typeof(UnityEngine.GameObject).Assembly; |
25 | | - engine.Runtime.LoadAssembly(unityEngine); |
26 | 27 |
|
27 | 28 | #if UNITY_EDITOR |
28 | | - var unityEditor = typeof(UnityEditor.Editor).Assembly; |
29 | | - engine.Runtime.LoadAssembly(unityEditor); |
| 29 | + // Load assemblies for the `UnityEditor*` namespaces |
| 30 | + foreach (var assembly in GetAssembliesInNamespace("UnityEditor")) |
| 31 | + { |
| 32 | + engine.Runtime.LoadAssembly(assembly); |
| 33 | + } |
30 | 34 | #endif |
31 | 35 |
|
32 | 36 | return engine; |
33 | 37 | } |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// Get a list of all loaded assemblies in the current AppDomain for a |
| 41 | + /// namespace beginning with the specified string. |
| 42 | + /// </summary> |
| 43 | + /// <param name="prefix">The beginning of the namespace.</param> |
| 44 | + /// <returns>All matching assemblies.</returns> |
| 45 | + private static IEnumerable<Assembly> GetAssembliesInNamespace(string prefix) |
| 46 | + { |
| 47 | + return AppDomain.CurrentDomain.GetAssemblies() |
| 48 | + .SelectMany(t => t.GetTypes()) |
| 49 | + .Where(t => t.Namespace != null && t.Namespace.StartsWith(prefix)) |
| 50 | + .Select(t => t.Assembly) |
| 51 | + .Distinct(); |
| 52 | + } |
34 | 53 | } |
0 commit comments