Component.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. protected override void OnDeleted()
  30. {
  31. if (subscribedToSceneUpdate)
  32. {
  33. Application.Update -= HandleUpdate;
  34. }
  35. base.OnDeleted();
  36. }
  37. internal void AttachedToNode(Node node)
  38. {
  39. if (!subscribedToSceneUpdate && ReceiveSceneUpdates)
  40. {
  41. subscribedToSceneUpdate = true;
  42. Application.Update += HandleUpdate;
  43. }
  44. OnAttachedToNode(node);
  45. }
  46. /// <summary>
  47. /// Make sure you set SubscribeToSceneUpdate property to true in order to receive Update events
  48. /// </summary>
  49. protected virtual void OnUpdate(float timeStep) { }
  50. internal static bool IsDefinedInManagedCode<T>() => typeof(T).GetRuntimeProperty("TypeStatic") == null;
  51. void HandleUpdate(UpdateEventArgs args)
  52. {
  53. OnUpdate(args.TimeStep);
  54. }
  55. }
  56. }