CollidersHandler.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace LunarCatsStudio.SuperCombiner
  5. {
  6. /// <summary>
  7. /// This class handles collider management
  8. /// </summary>
  9. public class CollidersHandler : MonoBehaviour
  10. {
  11. /// <summary>
  12. /// Create a new GameObject with collider element based on the original Collider element in paramter
  13. /// </summary>
  14. /// <param name="parent"></param>
  15. /// <param name="originalCollider"></param>
  16. /// <returns></returns>
  17. public static GameObject CreateNewCollider(Transform parent, Collider originalCollider)
  18. {
  19. // Instantiate the new GameObject containing the new collider
  20. GameObject newCollider = new GameObject(originalCollider.name);
  21. newCollider.transform.parent = parent.transform;
  22. newCollider.transform.position = originalCollider.transform.position;
  23. newCollider.transform.rotation = originalCollider.transform.rotation;
  24. newCollider.transform.localScale = originalCollider.transform.localScale;
  25. // Add the correct Collider Component type
  26. System.Type colliderType = originalCollider.GetType();
  27. if (colliderType == typeof(BoxCollider))
  28. {
  29. newCollider.AddComponent<BoxCollider>();
  30. }
  31. else if (colliderType == typeof(SphereCollider))
  32. {
  33. newCollider.AddComponent<SphereCollider>();
  34. }
  35. else if (colliderType == typeof(CapsuleCollider))
  36. {
  37. newCollider.AddComponent<CapsuleCollider>();
  38. }
  39. else if (colliderType == typeof(MeshCollider))
  40. {
  41. newCollider.AddComponent<MeshCollider>();
  42. }
  43. else if (colliderType == typeof(TerrainCollider))
  44. {
  45. newCollider.AddComponent<TerrainCollider>();
  46. }
  47. Collider colliderCopy = newCollider.GetComponent<Collider>();
  48. System.Reflection.FieldInfo[] fields = colliderType.GetFields();
  49. foreach (System.Reflection.FieldInfo field in fields)
  50. {
  51. field.SetValue(colliderCopy, field.GetValue(originalCollider));
  52. }
  53. foreach (var prop in colliderType.GetProperties())
  54. {
  55. if (prop.CanWrite && !prop.Name.Equals("name"))
  56. {
  57. prop.SetValue(colliderCopy, prop.GetValue(originalCollider, null), null);
  58. }
  59. }
  60. return newCollider;
  61. }
  62. }
  63. }