Component.cs 1.4 KB

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