GameObjectExtensions.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // ----------------------------------------------------------------------
  2. // File: GameObjectExtensions
  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.Reflection;
  10. namespace Virtence.VText.Extensions {
  11. /// <summary>
  12. /// some extensions to game objects
  13. /// </summary>
  14. public static class GameObjectExtensions
  15. {
  16. #region EVENTS
  17. #endregion // EVENTS
  18. #region CONSTANTS
  19. #endregion // CONSTANTS
  20. #region FIELDS
  21. #endregion // FIELDS
  22. #region PROPERTIES
  23. #endregion // PROPERTIES
  24. #region CONSTRUCTORS
  25. #endregion // CONSTRUCTORS
  26. #region METHODS
  27. /// <summary>
  28. /// Adds the component of type and sets the values corresponding to "toAdd"s values)
  29. /// </summary>
  30. /// <returns>The component.</returns>
  31. /// <param name="go">Go.</param>
  32. /// <param name="toAdd">To add.</param>
  33. /// <typeparam name="T">The 1st type parameter.</typeparam>
  34. public static Component AddComponentClone(this GameObject go, Component toAdd)
  35. {
  36. Component copy = System.ObjectExtensions.Copy<Component>(toAdd);
  37. object clone = null;
  38. if (copy != null) {
  39. clone = go.AddComponent(copy.GetType());
  40. System.Reflection.FieldInfo[] fields = clone.GetType().GetFields();
  41. foreach (System.Reflection.FieldInfo field in fields)
  42. {
  43. field.SetValue(clone, field.GetValue(toAdd));
  44. }
  45. var props = clone.GetType().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
  46. foreach (var prop in props)
  47. {
  48. if (!prop.CanWrite || !prop.CanWrite || prop.Name == "name") continue;
  49. prop.SetValue(clone, prop.GetValue(toAdd, null), null);
  50. }
  51. }
  52. return copy;
  53. }
  54. #endregion // METHODS
  55. #region EVENT HANDLERS
  56. #endregion // EVENT HANDLERS
  57. }
  58. }