forked from ss13remake/ss13remake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ComponentFactory.cs
56 lines (49 loc) · 2.26 KB
/
ComponentFactory.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace GameObject
{
public class ComponentFactory
{
private readonly string _componentNamespace;
private readonly List<Type> _types;
public ComponentFactory(EntityManager entityManager, string componentNamespace)
{
EntityManager = entityManager;
_componentNamespace = componentNamespace;
Type type = typeof (IComponent);
List<Assembly> asses = AppDomain.CurrentDomain.GetAssemblies().ToList();
_types = asses.SelectMany(t => t.GetTypes()).Where(p => type.IsAssignableFrom(p)).ToList();
}
public EntityManager EntityManager { get; private set; }
/// <summary>
/// Gets a new component instantiated of the specified type.
/// </summary>
/// <param name="componentType">type of component to make</param>
/// <returns>A Component</returns>
public IComponent GetComponent(Type componentType)
{
if (componentType.GetInterface("IComponent") == null)
return null;
return (IComponent) Activator.CreateInstance(componentType);
}
/// <summary>
/// Gets a new component instantiated of the specified type.
/// </summary>
/// <param name="componentType">type of component to make</param>
/// <returns>A Component</returns>
public IComponent GetComponent(string componentTypeName)
{
if (string.IsNullOrWhiteSpace(componentTypeName))
return null;
string fullName = _componentNamespace + "." + componentTypeName;
//Type t = Assembly.GetExecutingAssembly().GetType(componentTypeName); //Get the type
Type t = _types.FirstOrDefault(type => type.FullName == fullName);
//Type t = Type.GetType(_componentNamespace + "." + componentTypeName); //Get the type
if (t == null || t.GetInterface("IComponent") == null)
throw new TypeLoadException("Cannot find specified component type: " + fullName);
return (IComponent) Activator.CreateInstance(t); // Return an instance
}
}
}