Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UnityNodeHolder.cs 2.0KB

9 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Reflection;
  3. using UnityEngine;
  4. namespace Svelto.ES
  5. {
  6. public abstract class BaseNodeHolder<NodeType>:MonoBehaviour, INodeHolder where NodeType : INode
  7. {
  8. public INode node { get { if (_node != null) return _node; else return _node = ReturnNode(); } }
  9. public INodeEnginesRoot engineRoot { set { _engineRoot = value; } }
  10. protected abstract NodeType ReturnNode();
  11. void Start()
  12. {
  13. if (_engineRoot != null)
  14. _engineRoot.Add(node);
  15. }
  16. NodeType _node;
  17. INodeEnginesRoot _engineRoot;
  18. }
  19. public abstract class UnityNodeHolder<NodeType>:BaseNodeHolder<NodeType> where NodeType : INode
  20. {
  21. protected abstract NodeType GenerateNode();
  22. override protected NodeType ReturnNode()
  23. {
  24. NodeType node = GenerateNode();
  25. FieldInfo[] fields = typeof(NodeType).GetFields(BindingFlags.Public | BindingFlags.Instance);
  26. for (int i = fields.Length - 1; i >=0 ; --i)
  27. {
  28. var field = fields[i];
  29. var component = transform.GetComponentsInChildren(field.FieldType, true); //can't use inactive components
  30. if (component.Length == 0)
  31. {
  32. Exception e = new Exception("Svelto.ES: An Entity must hold all the components needed for a Node. Type: " + field.FieldType.Name + "Entity name: " + name);
  33. Debug.LogException(e, gameObject);
  34. throw e;
  35. }
  36. if (component.Length > 1)
  37. {
  38. Exception e = new Exception("Svelto.ES: An Entity can hold only one component of the same type. Type: " + field.FieldType.Name + "Entity name: " + name);
  39. Debug.LogException(e, gameObject);
  40. throw e;
  41. }
  42. field.SetValue(node, component[0]);
  43. }
  44. return node;
  45. }
  46. }
  47. }