ChangeCapsuleMaterial.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. // Use Script in parent Folder of all humans
  4. public class ChangeCapsuleMaterial : MonoBehaviour
  5. {
  6. public Material highlightRed;
  7. public Material highlightGreen;
  8. public Material highlightYellow;
  9. public int threshold = 1;
  10. public float radius = 1f;
  11. private Vector3 center;
  12. private Collider[] hitHumans;
  13. private List<Component> allHumansTransform = new List<Component>(); // only first depth children of parent (Humans)
  14. // Start is called before the first frame update
  15. private void Start()
  16. {
  17. Component[] allTransform = GetComponentsInChildren<Transform>(); // all possible children of parent object
  18. foreach (Transform child in allTransform)
  19. {
  20. if (child.parent == allTransform[0])
  21. {
  22. allHumansTransform.Add(child);
  23. }
  24. }
  25. //foreach (Component lst in allHumansTransform)
  26. //{
  27. // Debug.Log(lst.gameObject.name);
  28. //}
  29. }
  30. private void Update()
  31. {
  32. foreach (Component lst in allHumansTransform)
  33. {
  34. center = lst.GetComponent<Transform>().position;
  35. // only collisions with Layer "Humans" are listed in "hitHumans"
  36. hitHumans = Physics.OverlapSphere(center, radius, LayerMask.GetMask("Humans"));
  37. // if Humans only hits themselves (threshold == 1) or nobody, then Material change to Green
  38. if (hitHumans.Length <= 1)
  39. {
  40. Debug.Log(lst.gameObject.name + " set to Green");
  41. lst.GetComponent<MeshRenderer>().material = highlightGreen;
  42. }
  43. // if Human hits lesser then threshold but is hitting minimum 1 other human, then Material change to Yellow
  44. else if (hitHumans.Length <= threshold)
  45. {
  46. Debug.Log(lst.gameObject.name + " set to Yellow");
  47. lst.transform.GetChild(0).GetChild(0).gameObject.GetComponent<SkinnedMeshRenderer>().material = highlightYellow;
  48. }
  49. else
  50. {
  51. // if Humans hits somebody else (threshold >= 1), then Material change to Red
  52. foreach (Collider hitHuman in hitHumans)
  53. {
  54. if (lst.gameObject.name != hitHuman.gameObject.name) // overlap with themselves
  55. {
  56. if (hitHuman.GetComponent<MeshRenderer>().material != highlightRed
  57. || lst.GetComponent<MeshRenderer>().material != highlightRed)
  58. {
  59. Debug.Log(lst.gameObject.name + " overlaps with " + hitHuman.gameObject.name);
  60. hitHuman.GetComponent<MeshRenderer>().material = highlightRed;
  61. lst.GetComponent<MeshRenderer>().material = highlightRed;
  62. }
  63. }
  64. }
  65. }
  66. }
  67. }
  68. }