Component.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // Component C# sugar
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. // Copyrigh 2015 Xamarin INc
  8. //
  9. using System.Linq;
  10. using System.Reflection;
  11. using Urho.Resources;
  12. namespace Urho
  13. {
  14. public partial class Component
  15. {
  16. bool subscribedToSceneUpdate;
  17. protected bool ReceiveSceneUpdates { get; set; }
  18. public T GetComponent<T> () where T : Component
  19. {
  20. Runtime.ValidateRefCounted(this);
  21. return (T)Node.Components.FirstOrDefault(c => c is T);
  22. }
  23. public Application Application => Application.Current;
  24. public virtual void OnSerialize(IComponentSerializer serializer) { }
  25. public virtual void OnDeserialize(IComponentDeserializer deserializer) { }
  26. public virtual void OnAttachedToNode(Node node) {}
  27. public virtual void OnSceneSet(Scene scene) { }
  28. public virtual void OnNodeSetEnabled() { }
  29. public virtual void OnCloned(Scene scene, Component originalComponent) { }
  30. protected override void OnDeleted()
  31. {
  32. if (subscribedToSceneUpdate)
  33. {
  34. Application.Update -= HandleUpdate;
  35. }
  36. base.OnDeleted();
  37. }
  38. internal void AttachedToNode(Node node)
  39. {
  40. if (!subscribedToSceneUpdate && ReceiveSceneUpdates)
  41. {
  42. subscribedToSceneUpdate = true;
  43. Application.Update += HandleUpdate;
  44. }
  45. OnAttachedToNode(node);
  46. }
  47. /// <summary>
  48. /// Make sure you set SubscribeToSceneUpdate property to true in order to receive Update events
  49. /// </summary>
  50. protected virtual void OnUpdate(float timeStep) { }
  51. internal static bool IsDefinedInManagedCode<T>() => typeof(T).GetRuntimeProperty("TypeStatic") == null;
  52. void HandleUpdate(UpdateEventArgs args)
  53. {
  54. OnUpdate(args.TimeStep);
  55. }
  56. }
  57. }