ChangeCubeMaterial.cs 2.4 KB

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