ComponentExtensions.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // ----------------------------------------------------------------------
  2. // File: ComponentExtensions
  3. // Organisation: Virtence GmbH
  4. // Department: Simulation Development
  5. // Copyright: © 2014 Virtence GmbH. All rights reserved
  6. // Author: Silvio Lange (silvio.lange@virtence.com)
  7. // ----------------------------------------------------------------------
  8. using UnityEngine;
  9. using System;
  10. using System.Reflection;
  11. using System.IO;
  12. using System.Runtime.Serialization.Formatters.Binary;
  13. namespace Virtence.VText.Extensions {
  14. /// <summary>
  15. ///
  16. /// </summary>
  17. public static class ComponentExtensions
  18. {
  19. #region EVENTS
  20. #endregion // EVENTS
  21. #region CONSTANTS
  22. #endregion // CONSTANTS
  23. #region FIELDS
  24. #endregion // FIELDS
  25. #region PROPERTIES
  26. #endregion // PROPERTIES
  27. #region CONSTRUCTORS
  28. #endregion // CONSTRUCTORS
  29. #region METHODS
  30. public static T GetCopyOf<T>(this Component comp, T other) where T : Component
  31. {
  32. Type type = comp.GetType();
  33. if (type != other.GetType()) return null; // type mis-match
  34. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
  35. PropertyInfo[] pinfos = type.GetProperties(flags);
  36. foreach (var pinfo in pinfos) {
  37. if (pinfo.CanWrite) {
  38. try {
  39. pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
  40. }
  41. catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific.
  42. }
  43. }
  44. FieldInfo[] finfos = type.GetFields(flags);
  45. foreach (var finfo in finfos) {
  46. finfo.SetValue(comp, finfo.GetValue(other));
  47. }
  48. return comp as T;
  49. }
  50. #endregion // METHODS
  51. #region EVENT HANDLERS
  52. #endregion // EVENT HANDLERS
  53. }
  54. }